├── .editorconfig ├── .gitattributes ├── .github ├── ISSUE_TEMPLATE │ └── bug_report.yml └── workflows │ ├── ci.yml │ ├── release.yml │ ├── renovate.yml │ └── semgrep.yml ├── .gitignore ├── Directory.Build.props ├── Directory.Packages.props ├── GitVersion.yml ├── LICENSE ├── README.md ├── build.ps1 ├── global.json ├── nuget.config ├── renovate.json └── src ├── EphemeralMongo.Tests ├── DownloadArchitectureHelperTests.cs ├── DownloadEditionHelperTests.cs ├── DownloadTargetHelperTests.cs ├── EphemeralMongo.Tests.csproj ├── IsExternalInit.cs ├── MongoRunnerPoolTests.cs ├── MongoRunnerTests.cs ├── ProcessArgumentTests.cs ├── XunitConstants.cs └── xunit.runner.json ├── EphemeralMongo.sln ├── EphemeralMongo.v2.Tests └── EphemeralMongo.v2.Tests.csproj ├── EphemeralMongo.v2 └── EphemeralMongo.v2.csproj └── EphemeralMongo ├── BaseMongoProcess.cs ├── Download ├── DownloadArchitectureHelper.cs ├── DownloadEditionHelper.cs ├── DownloadTargetHelper.cs ├── FileCompressionHelper.cs ├── FileHashHelper.cs ├── MongoArchiveDto.cs ├── MongoDownloadDto.cs ├── MongoExecutableDownloader.cs ├── MongoVersionDto.cs ├── MongoVersionsDto.cs ├── NamedMutex.cs ├── RuntimeInformationHelper.cs ├── ToolsArchiveDto.cs ├── ToolsDownloadDto.cs ├── ToolsVersionDto.cs └── ToolsVersionsDto.cs ├── EphemeralMongo.csproj ├── EphemeralMongoException.cs ├── ExperimentalAttribute.cs ├── FileSystem.cs ├── HttpTransport.cs ├── IFileSystem.cs ├── IMongoExecutableLocator.cs ├── IMongoProcess.cs ├── IMongoProcessFactory.cs ├── IMongoRunner.cs ├── IPortFactory.cs ├── ITimeProvider.cs ├── Logger.cs ├── MongoEdition.cs ├── MongoExecutableLocator.cs ├── MongoImportExportProcess.cs ├── MongoProcessFactory.cs ├── MongoProcessKind.cs ├── MongoRunner.cs ├── MongoRunnerOptions.cs ├── MongoRunnerPool.cs ├── MongoVersion.cs ├── MongodProcess.cs ├── NativeMethods.cs ├── NativeMethods.txt ├── PortFactory.cs ├── ProcessArgument.cs ├── PublicAPI.Shipped.txt ├── PublicAPI.Unshipped.txt └── TimeProvider.cs /.editorconfig: -------------------------------------------------------------------------------- 1 | # Partially copied from the .NET runtime repository: 2 | # https://github.com/dotnet/runtime/blob/v8.0.0/.editorconfig 3 | 4 | root = true 5 | 6 | # Default settings: 7 | # A newline ending every file 8 | # Use 4 spaces as indentation 9 | [*] 10 | insert_final_newline = true 11 | indent_style = space 12 | indent_size = 4 13 | trim_trailing_whitespace = true 14 | charset = utf-8 15 | 16 | # Xml project files 17 | [*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,nativeproj,locproj}] 18 | indent_size = 2 19 | ij_xml_space_inside_empty_tag = true 20 | 21 | # Xml files 22 | [*.{xml,stylecop,resx,ruleset}] 23 | indent_size = 2 24 | ij_xml_space_inside_empty_tag = true 25 | 26 | # Xml config files 27 | [*.{props,targets,config,nuspec,conf}] 28 | indent_size = 2 29 | ij_xml_space_inside_empty_tag = true 30 | 31 | # YAML config files 32 | [*.{yml,yaml}] 33 | indent_size = 2 34 | 35 | # Shell scripts 36 | [*.{sh,ps1,psm1}] 37 | end_of_line = lf 38 | indent_size = 2 39 | 40 | [*.{cmd,bat}] 41 | end_of_line = crlf 42 | indent_size = 2 43 | 44 | # JSON 45 | [*.{json,json5,jsonc}] 46 | indent_size = 2 47 | 48 | # JavaScript and TypeScript 49 | [*.{js,ts,jsx,tsx}] 50 | indent_size = 2 51 | 52 | # CSS, SCSS and LESS 53 | [*.{css,scss,less}] 54 | indent_size = 2 55 | 56 | 57 | [*.cs] 58 | insert_final_newline = false 59 | 60 | # CA2007: Consider calling ConfigureAwait on the awaited task 61 | dotnet_diagnostic.CA2007.severity = warning -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Set the default behavior, in case users don't have core.autocrlf set. 2 | * text=auto 3 | 4 | # Files that should always be normalized and converted to native line endings on checkout. 5 | *.js text 6 | *.json text 7 | *.ts text 8 | *.tsx text 9 | *.md text 10 | *.sh text eol=lf 11 | *.conf text eol=lf 12 | *.yml text eol=lf 13 | *.yaml text eol=lf 14 | *.Dockerfile text eol=lf 15 | LICENSE text eol=lf -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.yml: -------------------------------------------------------------------------------- 1 | name: 🐞 Bug Report 2 | description: Create a report about something that is not working 3 | labels: ["bug"] 4 | body: 5 | - type: input 6 | id: version 7 | attributes: 8 | label: Version 9 | description: What version of EphemeralMongo are you using? 10 | placeholder: "Example: 2.0.0" 11 | validations: 12 | required: true 13 | - type: input 14 | id: packages 15 | attributes: 16 | label: Packages 17 | description: What package(s) of EphemeralMongo are you using? 18 | placeholder: "Example: EphemeralMongo.v2, EphemeralMongo8" 19 | validations: 20 | required: false 21 | - type: input 22 | id: os 23 | attributes: 24 | label: Operating System 25 | description: What operating system are you using? 26 | placeholder: "Example: Ubuntu 24.04, macOS 15" 27 | validations: 28 | required: true 29 | - type: input 30 | id: arch 31 | attributes: 32 | label: CPU architecture 33 | description: What CPU architecture are you using? 34 | placeholder: "Example: x64, ARM64" 35 | validations: 36 | required: false 37 | - type: input 38 | id: context 39 | attributes: 40 | label: Context 41 | description: Where are you using EphemeralMongo? 42 | placeholder: "Example: local environment, CI on GitHub Actions, or Azure Pipelines" 43 | validations: 44 | required: true 45 | - type: textarea 46 | id: description 47 | attributes: 48 | label: What happened? 49 | description: A clear and concise description of what the bug is, ideally with a code sample or steps to reproduce the issue. 50 | validations: 51 | required: true 52 | 53 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | workflow_dispatch: 5 | push: 6 | branches: [main] 7 | paths-ignore: ["*.md"] 8 | pull_request: 9 | branches: [main] 10 | paths-ignore: ["*.md"] 11 | 12 | jobs: 13 | ci: 14 | runs-on: ${{ matrix.os }} 15 | strategy: 16 | matrix: 17 | os: [ubuntu-24.04, ubuntu-22.04, macos-14, windows-2019] 18 | fail-fast: false 19 | steps: 20 | - uses: actions/checkout@v4 21 | with: 22 | fetch-depth: 0 23 | 24 | - uses: actions/setup-dotnet@v4 25 | 26 | # https://www.mongodb.com/docs/manual/tutorial/install-mongodb-enterprise-on-ubuntu-tarball/#prerequisites 27 | - if: matrix.os == 'ubuntu-24.04' 28 | run: | 29 | sudo apt-get install libcurl4 libgssapi-krb5-2 libldap2 libwrap0 libsasl2-2 libsasl2-modules libsasl2-modules-gssapi-mit snmp openssl liblzma5 30 | 31 | # https://www.mongodb.com/docs/manual/tutorial/install-mongodb-enterprise-on-ubuntu-tarball/#prerequisites 32 | - if: matrix.os == 'ubuntu-22.04' 33 | run: | 34 | sudo apt-get install libcurl4 libgssapi-krb5-2 libldap-2.5-0 libwrap0 libsasl2-2 libsasl2-modules libsasl2-modules-gssapi-mit snmp openssl liblzma5 35 | 36 | - if: matrix.os == 'ubuntu-24.04' 37 | run: ./build.ps1 38 | shell: pwsh 39 | env: 40 | NUGET_SOURCE: ${{ secrets.MYGET_SOURCE }} 41 | NUGET_API_KEY: ${{ secrets.MYGET_API_KEY }} 42 | 43 | - if: matrix.os != 'ubuntu-24.04' 44 | run: ./build.ps1 45 | shell: pwsh 46 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | tags: ["*"] 6 | 7 | jobs: 8 | release: 9 | runs-on: ubuntu-24.04 10 | steps: 11 | - uses: actions/checkout@v4 12 | with: 13 | fetch-depth: 0 14 | 15 | - uses: actions/setup-dotnet@v4 16 | 17 | # https://www.mongodb.com/docs/manual/tutorial/install-mongodb-enterprise-on-ubuntu-tarball/#prerequisites 18 | - run: | 19 | sudo apt-get install libcurl4 libgssapi-krb5-2 libldap2 libwrap0 libsasl2-2 libsasl2-modules libsasl2-modules-gssapi-mit snmp openssl liblzma5 20 | 21 | - run: ./build.ps1 22 | shell: pwsh 23 | env: 24 | NUGET_SOURCE: ${{ secrets.NUGET_SOURCE }} 25 | NUGET_API_KEY: ${{ secrets.NUGET_API_KEY }} 26 | -------------------------------------------------------------------------------- /.github/workflows/renovate.yml: -------------------------------------------------------------------------------- 1 | name: Renovate 2 | 3 | on: 4 | workflow_dispatch: {} 5 | schedule: 6 | - cron: "7 2 * * *" 7 | 8 | jobs: 9 | renovate: 10 | runs-on: ubuntu-24.04 11 | steps: 12 | - name: Checkout repository 13 | uses: actions/checkout@v4 14 | 15 | - name: Use Node.js 16 | uses: actions/setup-node@v4 17 | with: 18 | node-version: 22 19 | 20 | - name: Renovate 21 | shell: bash 22 | run: npx renovate $GITHUB_REPOSITORY 23 | env: 24 | RENOVATE_CONFIG_FILE: "renovate.json" 25 | RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }} 26 | LOG_LEVEL: "debug" 27 | -------------------------------------------------------------------------------- /.github/workflows/semgrep.yml: -------------------------------------------------------------------------------- 1 | name: Semgrep scan 2 | 3 | on: 4 | pull_request: 5 | branches: [main] 6 | workflow_dispatch: {} 7 | schedule: 8 | - cron: "50 21 * * 6" 9 | 10 | jobs: 11 | semgrep: 12 | runs-on: ubuntu-24.04 13 | 14 | # https://docs.github.com/en/code-security/code-scanning/integrating-with-code-scanning/uploading-a-sarif-file-to-github#example-workflow-for-sarif-files-generated-outside-of-a-repository 15 | permissions: 16 | security-events: write 17 | 18 | container: 19 | image: returntocorp/semgrep 20 | 21 | steps: 22 | - name: Checkout all commits and tags 23 | uses: actions/checkout@v4 24 | if: ${{ github.event_name == 'pull_request' }} 25 | with: 26 | fetch-depth: 0 27 | 28 | - name: Checkout single commit 29 | uses: actions/checkout@v4 30 | if: ${{ github.event_name != 'pull_request' }} 31 | 32 | - name: Pull request scan 33 | if: ${{ github.event_name == 'pull_request' }} 34 | run: semgrep scan --config=auto --verbose --time --error --baseline-commit ${{ github.event.pull_request.base.sha }} 35 | 36 | - name: Full scan 37 | if: ${{ github.event_name != 'pull_request' }} 38 | run: semgrep scan --config=auto --verbose --time --sarif --output report.sarif 39 | 40 | - name: Save report as pipeline artifact 41 | if: ${{ github.event_name != 'pull_request' }} 42 | uses: actions/upload-artifact@v4 43 | with: 44 | name: report.sarif 45 | path: report.sarif 46 | 47 | - name: Publish code scanning alerts 48 | if: ${{ github.event_name != 'pull_request' }} 49 | uses: github/codeql-action/upload-sarif@v3 50 | with: 51 | sarif_file: report.sarif 52 | category: semgrep 53 | -------------------------------------------------------------------------------- /.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 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.tlog 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # Visual Studio History (VSHistory) files 354 | .vshistory/ 355 | 356 | # BeatPulse healthcheck temp database 357 | healthchecksdb 358 | 359 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 360 | MigrationBackup/ 361 | 362 | # Ionide (cross platform F# VS Code tools) working folder 363 | .ionide/ 364 | 365 | # Fody - auto-generated XML schema 366 | FodyWeavers.xsd 367 | 368 | # Local History for Visual Studio Code 369 | .history/ 370 | 371 | # Windows Installer files from build outputs 372 | *.cab 373 | *.msi 374 | *.msix 375 | *.msm 376 | *.msp 377 | 378 | # JetBrains Rider 379 | .idea/ 380 | *.sln.iml 381 | 382 | # OS junk 383 | .DS_Store 384 | Desktop.ini 385 | ehthumbs.db 386 | Thumbs.db 387 | $RECYCLE.BIN/ 388 | 389 | # Cake 390 | build/tools/** 391 | !build/tools/packages.config 392 | 393 | # MongoDB tools 394 | /src/EphemeralMongo.Runtimes/runtimes/** 395 | /.output/ -------------------------------------------------------------------------------- /Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | Copyright © Anthony Simmon $([System.DateTime]::UtcNow.ToString(yyyy)) 4 | Anthony Simmon 5 | Anthony Simmon 6 | https://github.com/asimmon/ephemeral-mongo 7 | Apache-2.0 8 | 12 9 | enable 10 | enable 11 | true 12 | MongoDB;Mongo;test;testing;unittest;integrationtest 13 | 14 | 15 | 16 | 17 | all 18 | runtime; build; native; contentfiles; analyzers 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /Directory.Packages.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | true 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /GitVersion.yml: -------------------------------------------------------------------------------- 1 | # On main, generate a prerelease version (like "1.0.4-preview.2") at each commit unless a tag is present 2 | mode: ContinuousDelivery 3 | 4 | # Use exact same NuGet package version as assembly informational format, without any additional suffix like the commit hash 5 | assembly-informational-format: "{SemVer}" 6 | 7 | branches: 8 | main: 9 | # Use "preview" for prerelease version suffix, like "1.0.4-preview.2" 10 | label: preview -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # EphemeralMongo 3 | 4 | [![ci](https://img.shields.io/github/actions/workflow/status/asimmon/ephemeral-mongo/ci.yml?logo=github&label=ci)](https://github.com/asimmon/ephemeral-mongo/actions/workflows/ci.yml) [![publish](https://img.shields.io/github/actions/workflow/status/asimmon/ephemeral-mongo/release.yml?logo=github&label=release)](https://github.com/asimmon/ephemeral-mongo/actions/workflows/release.yml) 5 | 6 | - [About](#about) 7 | - [Installation](#installation) 8 | - [Usage](#usage) 9 | - [How it works](#how-it-works) 10 | - [MongoDB Enterprise and in-memory storage engine](#mongodb-enterprise-and-in-memory-storage-engine) 11 | - [Windows Defender Firewall prompt](#windows-defender-firewall-prompt) 12 | - [Reusing runners across tests](#reusing-runners-across-tests) 13 | - [Changelog](#changelog) 14 | 15 | ## About 16 | 17 | **EphemeralMongo** is a .NET library that provides a simple way to run temporary and disposable MongoDB servers for integration tests and local debugging, without any dependencies or external tools. It is as simple as: 18 | 19 | ```csharp 20 | using var runner = await MongoRunner.RunAsync(); 21 | Console.WriteLine(runner.ConnectionString); 22 | ``` 23 | 24 | Use the resulting connection string to access the MongoDB server. It will automatically be stopped and cleaned up when the `runner` is disposed. You can pass options to customize the server, such as the data directory, port, and replica set configuration. More details can be found in the [usage section](#usage). 25 | 26 | List of features and capabilities: 27 | 28 | - Multiple ephemeral and **isolated MongoDB databases** for running tests. 29 | - A quick way to set up a MongoDB database for a local development environment. 30 | - Access to **MongoDB 6**, **7**, and **8**. 31 | - Access to **MongoDB Community** and **Enterprise editions**. 32 | - Support for **single-node replica sets**, enabling transactions and change streams. 33 | - _mongoexport_ and _mongoimport_ tools for [exporting](https://www.mongodb.com/docs/database-tools/mongoexport/) and [importing](https://docs.mongodb.com/database-tools/mongoimport/) collections. 34 | - Support for .NET Standard 2.0, .NET Standard 2.1, .NET 8.0 and later. 35 | - Support for Linux, macOS, and Windows. 36 | - Supports **MongoDB C# driver version 2.x and 3.x**. 37 | 38 | This project follows in the footsteps of [Mongo2Go](https://github.com/Mongo2Go/Mongo2Go) and expands upon its foundation. 39 | 40 | ## Installation 41 | 42 | | Package | Description | 43 | | --- | --- | 44 | | [![nuget](https://img.shields.io/nuget/v/EphemeralMongo.svg?logo=nuget)](https://www.nuget.org/packages/EphemeralMongo/) | Install this package if you use MongoDB C# driver version 3.x. | 45 | | [![nuget](https://img.shields.io/nuget/v/EphemeralMongo.v2.svg?logo=nuget)](https://www.nuget.org/packages/EphemeralMongo.v2/) | Install this package if you use MongoDB C# driver version 2.x. | 46 | 47 | ## Usage 48 | 49 | Use `MongoRunner.RunAsync()` or `MongoRunner.Run()` methods to create a disposable instance that provides access to a **MongoDB connection string**, **import**, and **export tools**. An optional `MongoRunnerOptions` parameter can be provided to customize the MongoDB server. 50 | 51 | ```csharp 52 | // All the following properties are OPTIONAL. 53 | var options = new MongoRunnerOptions 54 | { 55 | // The desired MongoDB version to download and use. 56 | // Possible values are V6, V7 and V8. Default is V8. 57 | Version = MongoVersion.V8, 58 | 59 | // The desired MongoDB edition to download and use. 60 | // Possible values are Community and Enterprise. Default is Community. 61 | Edition = MongoEdition.Community, 62 | 63 | // If true, the MongoDB server will run as a single-node replica set. Default is false. 64 | UseSingleNodeReplicaSet = true, 65 | 66 | // Additional arguments to pass to the MongoDB server. Default is null. 67 | AdditionalArguments = ["--quiet"], 68 | 69 | // The port on which the MongoDB server will listen. 70 | // Default is null, which means a random available port will be assigned. 71 | MongoPort = 27017, 72 | 73 | // The directory where the MongoDB server will store its data. 74 | // Default is null, which means a temporary directory will be created. 75 | DataDirectory = "/path/to/data/", 76 | 77 | // Provide your own MongoDB binaries in this directory. 78 | // Default is null, which means the library will download them automatically. 79 | BinaryDirectory = "/path/to/mongo/bin/", 80 | 81 | // A delegate that receives the MongoDB server's standard output. 82 | StandardOutputLogger = Console.WriteLine, 83 | 84 | // A delegate that receives the MongoDB server's standard error output. 85 | StandardErrorLogger = Console.WriteLine, 86 | 87 | // Timeout for the MongoDB server to start. Default is 30 seconds. 88 | ConnectionTimeout = TimeSpan.FromSeconds(10), 89 | 90 | // Timeout for the replica set to be initialized. Default is 10 seconds. 91 | ReplicaSetSetupTimeout = TimeSpan.FromSeconds(5), 92 | 93 | // The duration for which temporary data directories will be kept. 94 | // Ignored when you provide your own data directory. Default is 12 hours. 95 | DataDirectoryLifetime = TimeSpan.FromDays(1), 96 | 97 | // Override this property to provide your own HTTP transport. 98 | // Useful when behind a proxy or firewall. Default is a shared reusable instance. 99 | Transport = new HttpTransport(new HttpClient()), 100 | 101 | // Delay before checking for a new version of the MongoDB server. Default is 1 day. 102 | NewVersionCheckTimeout = TimeSpan.FromDays(2) 103 | }; 104 | ``` 105 | 106 | ```csharp 107 | // Disposing the runner will kill the MongoDB process (mongod) and delete the associated data directory 108 | using (await var runner = MongoRunner.RunAsync(options)) 109 | { 110 | var database = new MongoClient(runner.ConnectionString).GetDatabase("default"); 111 | 112 | // Do something with the database 113 | database.CreateCollection("people"); 114 | 115 | // Export a collection to a file. A synchronous version is also available. 116 | await runner.ExportAsync("default", "people", "/path/to/default.json"); 117 | 118 | // Import a collection from a file. A synchronous version is also available. 119 | await runner.ImportAsync("default", "people", "/path/to/default.json"); 120 | } 121 | ``` 122 | 123 | ## How it works 124 | 125 | * At runtime, the MongoDB binaries (`mongod`, `mongoimport`, and `mongoexport`) are downloaded when needed (if not already present) and extracted to your local application data directory. 126 | * Official download links are retrieved from [this JSON file](https://downloads.mongodb.org/current.json) for the server and [this JSON file](https://downloads.mongodb.org/tools/db/release.json) for the tools. 127 | * SHA256 checksums are used to verify the integrity of the downloaded files. 128 | * `MongoRunner.Run` or `MongoRunner.RunAsync` always starts a new `mongod` process with a random available port. 129 | * The resulting connection string will depend on your options (`UseSingleNodeReplicaSet`). 130 | * By default, a unique temporary data directory is used and deleted when the `runner` is disposed. 131 | 132 | ## MongoDB Enterprise and in-memory storage engine 133 | 134 | Make sure you are allowed to use MongoDB Enterprise binaries in your projects. The [official download page](https://www.mongodb.com/try/download/enterprise) states: 135 | 136 | > MongoDB Enterprise Server is also available free of charge for evaluation and development purposes. 137 | 138 | The Enterprise edition provides access to the in-memory storage engine, which is faster and more efficient for tests: 139 | 140 | ```csharp 141 | var options = new MongoRunnerOptions 142 | { 143 | Edition = MongoEdition.Enterprise, 144 | AdditionalArguments = ["--storageEngine", "inMemory"], 145 | }; 146 | 147 | using var runner = await MongoRunner.RunAsync(options); 148 | // [...] 149 | ``` 150 | 151 | ## Windows Defender Firewall prompt 152 | 153 | On Windows, you might get a **Windows Defender Firewall prompt**. 154 | This is because EphemeralMongo starts the `mongod.exe` process from your local app data directory, and `mongod.exe` tries to open an available port. 155 | 156 | ## Reusing runners across tests 157 | 158 | Avoid calling `MongoRunner.Run` or `MongoRunner.RunAsync` concurrently, as this will create many `mongod` processes and make your operating system slower. Instead, try to use a single instance and reuse it - create as many databases as you need, one per test, for example. 159 | 160 | For this, version 3.0.0 introduces a new *experimental* `PooledMongoRunner` class. Once created, you can rent and return `MongoRunner` instances. Once rented a certain number of times, new instances will be created. This way, `mongod` processes will be reused, but not too often. This will avoid uncontrolled usage of system resources. 161 | 162 | ```csharp 163 | var options = new MongoRunnerOptions 164 | { 165 | Version = MongoVersion.V7, 166 | UseSingleNodeReplicaSet = true 167 | }; 168 | 169 | using var pool = new MongoRunnerPool(options); 170 | 171 | var runner1 = await pool.RentAsync(); 172 | var runner2 = await pool.RentAsync(); 173 | 174 | try 175 | { 176 | // Same connection string, same mongod process 177 | Console.WriteLine(runner1.ConnectionString); 178 | Console.WriteLine(runner2.ConnectionString); 179 | } 180 | finally 181 | { 182 | pool.Return(runner1); 183 | pool.Return(runner2); 184 | } 185 | 186 | // This is a new mongod process 187 | var runner3 = await pool.RentAsync(); 188 | ``` 189 | 190 | ## Changelog 191 | 192 | ### 3.0.0 193 | 194 | See [this announcement](https://github.com/asimmon/ephemeral-mongo/issues/80). 195 | 196 | ### 2.0.0 197 | 198 | - **Breaking change**: Support for MongoDB 5.0 and 6.0 has been removed, as their [end-of-life](https://www.mongodb.com/legal/support-policy/lifecycles) has passed. 199 | - **Breaking change**: arm64 is now the default target for macOS. The previous target was x64. 200 | - **Breaking change**: The Linux runtime package now uses Ubuntu 22.04's MongoDB binaries instead of the 18.04 ones. OpenSSL 3.0 is now required. 201 | - **Breaking change**: Updated the MongoDB C# driver to 2.28.0, [which now uses strong-named assemblies](https://www.mongodb.com/community/forums/t/net-driver-2-28-0-released/289745). 202 | - Added support for MongoDB 8.0. 203 | - Introduced data directory management to delete old data directories automatically. 204 | - Use direct connection in replica set connection strings. 205 | - Fixed the spelling issue in `MongoRunnerOptions.StandardOutputLogger`. 206 | -------------------------------------------------------------------------------- /build.ps1: -------------------------------------------------------------------------------- 1 | #Requires -Version 5.0 2 | 3 | Begin { 4 | $ErrorActionPreference = "stop" 5 | } 6 | 7 | Process { 8 | function Exec([scriptblock]$Command) { 9 | & $Command 10 | if ($LASTEXITCODE -ne 0) { 11 | throw ("An error occurred while executing command: {0}" -f $Command) 12 | } 13 | } 14 | 15 | $workingDir = Join-Path $PSScriptRoot "src" 16 | $outputDir = Join-Path $PSScriptRoot ".output" 17 | $nupkgsPath = Join-Path $outputDir "*.nupkg" 18 | 19 | try { 20 | Push-Location $workingDir 21 | Remove-Item $outputDir -Force -Recurse -ErrorAction SilentlyContinue 22 | 23 | Exec { & dotnet clean -c Release } 24 | 25 | Exec { & dotnet build -c Release } 26 | 27 | # https://learn.microsoft.com/en-us/dotnet/core/testing/microsoft-testing-platform-integration-dotnet-test 28 | # https://github.com/microsoft/testfx/issues/4396 29 | if ($IsWindows) { 30 | Exec { & dotnet test -c Release --no-build --no-restore -p:TestingPlatformShowTestsFailure=true -p:TestingPlatformCaptureOutput=false -tl:false -- --filter-query "/[Category!=SlowOnWindows]" } 31 | } else { 32 | Exec { & dotnet test -c Release --no-build --no-restore -p:TestingPlatformShowTestsFailure=true -p:TestingPlatformCaptureOutput=false -tl:false } 33 | } 34 | 35 | Exec { & dotnet pack -c Release --no-build --output "$outputDir" } 36 | 37 | if (($null -ne $env:NUGET_SOURCE ) -and ($null -ne $env:NUGET_API_KEY)) { 38 | Exec { & dotnet nuget push "$nupkgsPath" -s $env:NUGET_SOURCE -k $env:NUGET_API_KEY --skip-duplicate } 39 | } 40 | } 41 | finally { 42 | Pop-Location 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /global.json: -------------------------------------------------------------------------------- 1 | { 2 | "sdk": { 3 | "version": "9.0.300", 4 | "rollForward": "latestPatch", 5 | "allowPrerelease": false 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /nuget.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "platform": "github", 4 | "labels": ["renovate"], 5 | "extends": [ 6 | "config:base", 7 | ":rebaseStalePrs" 8 | ], 9 | "enabledManagers": [ 10 | "github-actions", 11 | "nuget" 12 | ], 13 | "stabilityDays": 3, 14 | "prHourlyLimit": 0, 15 | "prConcurrentLimit": 0, 16 | "branchConcurrentLimit": 0, 17 | "dependencyDashboard": false, 18 | "gitAuthor": "Renovate Bot ", 19 | "packageRules": [ 20 | { 21 | "matchManagers": ["nuget"], 22 | "groupName": "NuGet dependencies" 23 | }, 24 | { 25 | "matchManagers": ["nuget"], 26 | "matchPackageNames": ["MongoDB.Driver"], 27 | "groupName": "Ignored MongoDB.Driver", 28 | "description": "We only set a minimum required version, any vulnerabilities will still be reported", 29 | "enabled": false 30 | }, 31 | { 32 | "matchPackageNames": ["dotnet-sdk"], 33 | "groupName": "Dotnet SDK", 34 | "description": "Only update patch and minor for the dotnet SDK version within the global.json", 35 | "extends": [":disableMajorUpdates"] 36 | }, 37 | { 38 | "matchManagers": ["github-actions"], 39 | "groupName": "Pipeline dependencies" 40 | } 41 | ], 42 | "vulnerabilityAlerts": { 43 | "enabled": true, 44 | "labels": ["security"] 45 | } 46 | } -------------------------------------------------------------------------------- /src/EphemeralMongo.Tests/DownloadArchitectureHelperTests.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.InteropServices; 2 | using EphemeralMongo.Download; 3 | 4 | namespace EphemeralMongo.Tests; 5 | 6 | public sealed class DownloadArchitectureHelperTests 7 | { 8 | [Fact] 9 | public void GetArchitecture_ReturnsCurrentArchitecture() 10 | { 11 | var result = DownloadArchitectureHelper.GetArchitecture(); 12 | var expected = DownloadArchitectureHelper.GetArchitecture(RuntimeInformation.ProcessArchitecture, RuntimeInformationHelper.OSPlatform); 13 | Assert.Equal(expected, result); 14 | } 15 | 16 | [Theory] 17 | [InlineData(Architecture.X86, "x86_64")] 18 | [InlineData(Architecture.X64, "x86_64")] 19 | public void GetArchitecture_ReturnsX86_64_ForX86AndX64(Architecture architecture, string expectedResult) 20 | { 21 | var result = DownloadArchitectureHelper.GetArchitecture(architecture, OSPlatform.Windows); 22 | Assert.Equal(expectedResult, result); 23 | } 24 | 25 | [Fact] 26 | public void GetArchitecture_ReturnsAarch64_ForArm64OnNonMacOS() 27 | { 28 | var result = DownloadArchitectureHelper.GetArchitecture(Architecture.Arm64, OSPlatform.Linux); 29 | Assert.Equal("aarch64", result); 30 | } 31 | 32 | [Fact] 33 | public void GetArchitecture_ReturnsArm64_ForArm64OnMacOS() 34 | { 35 | var result = DownloadArchitectureHelper.GetArchitecture(Architecture.Arm64, OSPlatform.OSX); 36 | Assert.Equal("arm64", result); 37 | } 38 | 39 | [Theory] 40 | [InlineData(Architecture.Arm)] 41 | #if NET9_0_OR_GREATER 42 | [InlineData(Architecture.Wasm)] 43 | [InlineData(Architecture.S390x)] 44 | [InlineData(Architecture.LoongArch64)] 45 | [InlineData(Architecture.Armv6)] 46 | [InlineData(Architecture.Ppc64le)] 47 | #endif 48 | [InlineData((Architecture)99)] // Some undefined architecture 49 | public void GetArchitecture_ThrowsPlatformNotSupportedException_ForUnsupportedArchitectures(Architecture architecture) 50 | { 51 | var exception = Assert.Throws(() => 52 | DownloadArchitectureHelper.GetArchitecture(architecture, OSPlatform.Windows)); 53 | Assert.Contains(architecture.ToString(), exception.Message); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/EphemeralMongo.Tests/DownloadEditionHelperTests.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.InteropServices; 2 | using EphemeralMongo.Download; 3 | 4 | namespace EphemeralMongo.Tests; 5 | 6 | public sealed class DownloadEditionHelperTests 7 | { 8 | [Fact] 9 | public void GetEdition_WithEditionOnly_ReturnsCorrectEdition() 10 | { 11 | var edition = MongoEdition.Enterprise; 12 | var result = DownloadEditionHelper.GetEdition(edition); 13 | var expected = DownloadEditionHelper.GetEdition(edition, RuntimeInformationHelper.OSPlatform); 14 | 15 | Assert.Equal(expected, result); 16 | } 17 | 18 | [Fact] 19 | public void GetEdition_EnterpriseEdition_AlwaysReturnsEnterprise() 20 | { 21 | // Enterprise edition should return "enterprise" regardless of platform 22 | var result1 = DownloadEditionHelper.GetEdition(MongoEdition.Enterprise, OSPlatform.Windows); 23 | var result2 = DownloadEditionHelper.GetEdition(MongoEdition.Enterprise, OSPlatform.OSX); 24 | var result3 = DownloadEditionHelper.GetEdition(MongoEdition.Enterprise, OSPlatform.Linux); 25 | 26 | Assert.Equal("enterprise", result1); 27 | Assert.Equal("enterprise", result2); 28 | Assert.Equal("enterprise", result3); 29 | } 30 | 31 | [Fact] 32 | public void GetEdition_CommunityEdition_ReturnsBaseOrTargeted() 33 | { 34 | // Community edition should return "targeted" for Linux, "base" for other platforms 35 | var result1 = DownloadEditionHelper.GetEdition(MongoEdition.Community, OSPlatform.Windows); 36 | var result2 = DownloadEditionHelper.GetEdition(MongoEdition.Community, OSPlatform.OSX); 37 | var result3 = DownloadEditionHelper.GetEdition(MongoEdition.Community, OSPlatform.Linux); 38 | 39 | Assert.Equal("base", result1); 40 | Assert.Equal("base", result2); 41 | Assert.Equal("targeted", result3); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/EphemeralMongo.Tests/DownloadTargetHelperTests.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.InteropServices; 2 | using System.Text; 3 | using EphemeralMongo.Download; 4 | 5 | namespace EphemeralMongo.Tests; 6 | 7 | public sealed class DownloadTargetHelperTests : IDisposable 8 | { 9 | private readonly string _tmpOsReleasePath; 10 | private readonly DownloadTargetHelper _helper; 11 | 12 | public DownloadTargetHelperTests() 13 | { 14 | this._tmpOsReleasePath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); 15 | this._helper = new DownloadTargetHelper(this._tmpOsReleasePath); 16 | } 17 | 18 | [Fact] 19 | public void GetTarget_ReturnsWindows_WhenOsPlatformIsWindows() 20 | { 21 | var target = this._helper.GetTarget(OSPlatform.Windows, MongoVersion.V8); 22 | Assert.Equal("windows", target); 23 | } 24 | 25 | [Fact] 26 | public void GetTarget_ReturnsMacOS_WhenOsPlatformIsOSX() 27 | { 28 | var target = this._helper.GetTarget(OSPlatform.OSX, MongoVersion.V8); 29 | Assert.Equal("macos", target); 30 | } 31 | 32 | [Theory] 33 | [InlineData("ubuntu", "18.04", "ubuntu1804")] 34 | [InlineData("ubuntu", "18.10", "ubuntu1804")] 35 | [InlineData("ubuntu", "19.04", "ubuntu1804")] 36 | [InlineData("ubuntu", "19.10", "ubuntu1804")] 37 | [InlineData("ubuntu", "20.04", "ubuntu2004")] 38 | [InlineData("ubuntu", "20.10", "ubuntu2004")] 39 | [InlineData("ubuntu", "21.04", "ubuntu2004")] 40 | [InlineData("ubuntu", "21.10", "ubuntu2004")] 41 | [InlineData("ubuntu", "22.04", "ubuntu2204")] 42 | [InlineData("ubuntu", "22.10", "ubuntu2204")] 43 | [InlineData("ubuntu", "23.04", "ubuntu2204")] 44 | [InlineData("ubuntu", "23.10", "ubuntu2204")] 45 | [InlineData("ubuntu", "24.04", "ubuntu2404")] 46 | [InlineData("debian", "10", "debian10")] 47 | [InlineData("debian", "10.5", "debian10")] 48 | [InlineData("debian", "11", "debian11")] 49 | [InlineData("debian", "11.6", "debian11")] 50 | [InlineData("debian", "12", "debian12")] 51 | [InlineData("debian", "12.1", "debian12")] 52 | [InlineData("opensuse-leap", "15.1", "suse15")] 53 | [InlineData("opensuse-leap", "15.3", "suse15")] 54 | [InlineData("opensuse-leap", "15.5", "suse15")] 55 | [InlineData("opensuse", "12.5", "suse12")] 56 | [InlineData("rhel", "7.0", "rhel70")] 57 | [InlineData("rhel", "7.1", "rhel70")] 58 | [InlineData("rhel", "7.2", "rhel72")] 59 | [InlineData("rhel", "7.5", "rhel72")] 60 | [InlineData("rhel", "7.9", "rhel72")] 61 | [InlineData("rhel", "8.0", "rhel8")] 62 | [InlineData("rhel", "8.1", "rhel81")] 63 | [InlineData("rhel", "8.2", "rhel81")] 64 | [InlineData("rhel", "8.3", "rhel83")] 65 | [InlineData("rhel", "8.5", "rhel83")] 66 | [InlineData("rhel", "9.0", "rhel90")] 67 | [InlineData("rhel", "9.1", "rhel90")] 68 | [InlineData("rhel", "9.2", "rhel90")] 69 | [InlineData("rhel", "9.3", "rhel93")] 70 | [InlineData("amzn", "2", "amazon2")] 71 | [InlineData("amzn", "2023", "amazon2023")] 72 | public void GetTarget_ReturnsLinuxTarget_WhenLinuxOsReleaseFileExists(string actualId, string actualVersionId, string expectedTarget) 73 | { 74 | this.CreateOsReleaseFile(actualId, actualVersionId); 75 | var target = this._helper.GetTarget(OSPlatform.Linux, MongoVersion.V8); 76 | Assert.Equal(expectedTarget, target); 77 | } 78 | 79 | [Theory] 80 | [InlineData("ubuntu", "24.04", "ubuntu2204", MongoVersion.V6)] 81 | [InlineData("ubuntu", "24.04", "ubuntu2204", MongoVersion.V7)] 82 | [InlineData("ubuntu", "24.04", "ubuntu2404", MongoVersion.V8)] 83 | public void GetTarget_AdjustsLinuxTarget_ForOlderMongoVersions(string actualId, string actualVersionId, string expectedTarget, MongoVersion version) 84 | { 85 | this.CreateOsReleaseFile(actualId, actualVersionId); 86 | var target = this._helper.GetTarget(OSPlatform.Linux, version); 87 | Assert.Equal(expectedTarget, target); 88 | } 89 | 90 | [Theory] 91 | [InlineData("ubuntu", "16.04")] 92 | [InlineData("ubuntu", "17.10")] 93 | [InlineData("debian", "9")] 94 | [InlineData("debian", "9.13")] 95 | [InlineData("opensuse-leap", "11.4")] 96 | [InlineData("rhel", "6.10")] 97 | [InlineData("rhel", "6.0")] 98 | [InlineData("amzn", "1")] 99 | [InlineData("amzn", "2022")] 100 | public void GetTarget_ThrowsNotSupportedException_WhenOsVersionIsInvalid(string id, string versionId) 101 | { 102 | this.CreateOsReleaseFile(id, versionId); 103 | var exception = Assert.Throws(() => this._helper.GetTarget(OSPlatform.Linux, MongoVersion.V8)); 104 | Assert.Contains(versionId, exception.Message); 105 | } 106 | 107 | [Fact] 108 | public void GetTarget_ReturnsFallbackTarget_WhenOsReleaseFileDoesNotExist() 109 | { 110 | var target = this._helper.GetTarget(OSPlatform.Linux, MongoVersion.V8); 111 | Assert.Equal("ubuntu2204", target); 112 | } 113 | 114 | [Theory] 115 | [InlineData("ubuntu")] 116 | [InlineData("debian")] 117 | [InlineData("opensuse-leap")] 118 | [InlineData("rhel")] 119 | [InlineData("amzn")] 120 | public void GetTarget_ReturnsFallbackTarget_WhenVersionIdIsMissing(string id) 121 | { 122 | this.CreateOsReleaseFile(id, versionId: null); 123 | var target = this._helper.GetTarget(OSPlatform.Linux, MongoVersion.V8); 124 | Assert.Equal("ubuntu2204", target); 125 | } 126 | 127 | [Theory] 128 | [InlineData("18.04")] 129 | [InlineData("20.04")] 130 | [InlineData("22.04")] 131 | [InlineData("10")] 132 | [InlineData("11")] 133 | [InlineData("15.3")] 134 | [InlineData("9.3")] 135 | [InlineData("2023")] 136 | public void GetTarget_ReturnsFallbackTarget_WhenIdIsMissing(string versionId) 137 | { 138 | this.CreateOsReleaseFile(id: null, versionId); 139 | var target = this._helper.GetTarget(OSPlatform.Linux, MongoVersion.V8); 140 | Assert.Equal("ubuntu2204", target); 141 | } 142 | 143 | [Fact] 144 | public void GetTarget_ReturnsFallbackTarget_WhenBothIdAndVersionIdAreMissing() 145 | { 146 | this.CreateOsReleaseFile(id: null, versionId: null); 147 | var target = this._helper.GetTarget(OSPlatform.Linux, MongoVersion.V8); 148 | Assert.Equal("ubuntu2204", target); 149 | } 150 | 151 | [Theory] 152 | [InlineData("fedora", "38")] 153 | [InlineData("centos", "9")] 154 | [InlineData("arch", "rolling")] 155 | [InlineData("manjaro", "23.1.0")] 156 | [InlineData("alpine", "3.18")] 157 | public void GetTarget_ReturnsFallbackTarget_WhenIdIsNotSupported(string id, string versionId) 158 | { 159 | this.CreateOsReleaseFile(id, versionId); 160 | var target = this._helper.GetTarget(OSPlatform.Linux, MongoVersion.V8); 161 | Assert.Equal("ubuntu2204", target); 162 | } 163 | 164 | #if NET9_0_OR_GREATER 165 | [Fact] 166 | public void GetTarget_ThrowsPlatformNotSupportedException_WhenOsPlatformIsUnsupported() 167 | { 168 | var unsupportedPlatform = OSPlatform.FreeBSD; 169 | Assert.Throws(() => this._helper.GetTarget(unsupportedPlatform, MongoVersion.V8)); 170 | } 171 | #endif 172 | 173 | private void CreateOsReleaseFile(string? id, string? versionId) 174 | { 175 | var sb = new StringBuilder(); 176 | 177 | sb.AppendLine("NAME=\"Not a real OS\""); 178 | 179 | if (id != null) 180 | { 181 | sb.AppendLine($"ID=\"{id}\""); 182 | } 183 | 184 | sb.AppendLine("PRETTY_NAME=\"Not a real OS\""); 185 | 186 | if (versionId != null) 187 | { 188 | sb.AppendLine($"VERSION_ID=\"{versionId}\""); 189 | } 190 | 191 | sb.AppendLine("FOO=\"bar\""); 192 | 193 | File.WriteAllText(this._tmpOsReleasePath, sb.ToString()); 194 | } 195 | 196 | public void Dispose() 197 | { 198 | try 199 | { 200 | File.Delete(this._tmpOsReleasePath); 201 | } 202 | catch (IOException) 203 | { 204 | // File will be cleaned up by the OS at some point 205 | } 206 | } 207 | } 208 | 209 | -------------------------------------------------------------------------------- /src/EphemeralMongo.Tests/EphemeralMongo.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net9.0 4 | Exe 5 | enable 6 | enable 7 | false 8 | $(NoWarn);CA2007 9 | true 10 | true 11 | EphemeralMongo.Tests 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /src/EphemeralMongo.Tests/IsExternalInit.cs: -------------------------------------------------------------------------------- 1 | #if NETFRAMEWORK 2 | using System.ComponentModel; 3 | 4 | #pragma warning disable IDE0130 // Namespace does not match folder structure 5 | namespace System.Runtime.CompilerServices; 6 | 7 | /// 8 | /// Reserved to be used by the compiler for tracking metadata. 9 | /// This class should not be used by developers in source code. 10 | /// 11 | [EditorBrowsable(EditorBrowsableState.Never)] 12 | internal static class IsExternalInit 13 | { 14 | } 15 | #endif -------------------------------------------------------------------------------- /src/EphemeralMongo.Tests/MongoRunnerPoolTests.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using System.Net.Sockets; 3 | using MongoDB.Bson; 4 | using MongoDB.Driver; 5 | 6 | #pragma warning disable EMEX0001 // Type is for evaluation purposes only 7 | 8 | namespace EphemeralMongo.Tests; 9 | 10 | [Trait(XunitConstants.Category, XunitConstants.SlowOnWindows)] 11 | public class MongoRunnerPoolTests(ITestContextAccessor testContextAccessor) 12 | { 13 | [Fact] 14 | public async Task RentAsync_Returns_New_Runner_When_Pool_Is_Empty() 15 | { 16 | // Arrange 17 | var options = CreateDefaultOptions(); 18 | 19 | // Act 20 | using var pool = new MongoRunnerPool(options); 21 | using var runner = await pool.RentAsync(testContextAccessor.Current.CancellationToken); 22 | 23 | // Assert 24 | Assert.NotNull(runner); 25 | Assert.NotNull(runner.ConnectionString); 26 | Assert.Contains("mongodb://127.0.0.1", runner.ConnectionString); 27 | 28 | // Verify server is running 29 | this.AssertServerUpAndReady(runner.ConnectionString); 30 | } 31 | 32 | [Fact] 33 | public void Rent_Returns_New_Runner_When_Pool_Is_Empty() 34 | { 35 | // Arrange 36 | var options = CreateDefaultOptions(); 37 | 38 | // Act 39 | using var pool = new MongoRunnerPool(options); 40 | using var runner = pool.Rent(testContextAccessor.Current.CancellationToken); 41 | 42 | // Assert 43 | Assert.NotNull(runner); 44 | Assert.NotNull(runner.ConnectionString); 45 | Assert.Contains("mongodb://127.0.0.1", runner.ConnectionString); 46 | 47 | // Verify server is running 48 | this.AssertServerUpAndReady(runner.ConnectionString); 49 | } 50 | 51 | [Fact] 52 | public async Task RentAsync_Reuses_Runner_When_Returned_And_Not_MaxedOut() 53 | { 54 | // Arrange 55 | var options = CreateDefaultOptions(); 56 | using var pool = new MongoRunnerPool(options, 2); 57 | 58 | // Act 59 | var runner1 = await pool.RentAsync(testContextAccessor.Current.CancellationToken); 60 | var runner2 = await pool.RentAsync(testContextAccessor.Current.CancellationToken); 61 | 62 | var connectionString1 = runner1.ConnectionString; 63 | var connectionString2 = runner2.ConnectionString; 64 | 65 | pool.Return(runner1); 66 | 67 | // Assert 68 | Assert.Equal(connectionString1, connectionString2); 69 | 70 | // Verify server is still running 71 | AssertServerDown(connectionString1); 72 | 73 | // Cleanup 74 | pool.Return(runner2); 75 | } 76 | 77 | [Fact] 78 | public void Rent_Reuses_Runner_When_Returned_And_Not_MaxedOut() 79 | { 80 | // Arrange 81 | var options = CreateDefaultOptions(); 82 | using var pool = new MongoRunnerPool(options, 2); 83 | 84 | // Act 85 | var runner1 = pool.Rent(testContextAccessor.Current.CancellationToken); 86 | var runner2 = pool.Rent(testContextAccessor.Current.CancellationToken); 87 | 88 | var connectionString1 = runner1.ConnectionString; 89 | var connectionString2 = runner2.ConnectionString; 90 | 91 | pool.Return(runner1); 92 | 93 | // Assert 94 | Assert.Equal(connectionString1, connectionString2); 95 | 96 | AssertServerDown(connectionString1); 97 | 98 | // Cleanup 99 | pool.Return(runner2); 100 | } 101 | 102 | [Fact] 103 | public async Task RentAsync_Creates_New_Runner_When_MaxRentals_Reached() 104 | { 105 | // Arrange 106 | var options = CreateDefaultOptions(); 107 | using var pool = new MongoRunnerPool(options, 1); 108 | 109 | // Act 110 | var runner1 = await pool.RentAsync(testContextAccessor.Current.CancellationToken); 111 | var connectionString1 = runner1.ConnectionString; 112 | pool.Return(runner1); 113 | 114 | var runner2 = await pool.RentAsync(testContextAccessor.Current.CancellationToken); 115 | var connectionString2 = runner2.ConnectionString; 116 | 117 | // Assert 118 | Assert.NotEqual(connectionString1, connectionString2); 119 | Assert.NotSame(runner1, runner2); 120 | 121 | // Verify server is running for the new runner 122 | this.AssertServerUpAndReady(runner2.ConnectionString); 123 | 124 | // Cleanup 125 | pool.Return(runner2); 126 | } 127 | 128 | [Fact] 129 | public void Rent_Creates_New_Runner_When_MaxRentals_Reached() 130 | { 131 | // Arrange 132 | var options = CreateDefaultOptions(); 133 | using var pool = new MongoRunnerPool(options, 1); 134 | 135 | // Act 136 | var runner1 = pool.Rent(testContextAccessor.Current.CancellationToken); 137 | var connectionString1 = runner1.ConnectionString; 138 | pool.Return(runner1); 139 | 140 | var runner2 = pool.Rent(testContextAccessor.Current.CancellationToken); 141 | var connectionString2 = runner2.ConnectionString; 142 | 143 | // Assert 144 | Assert.NotEqual(connectionString1, connectionString2); 145 | Assert.NotSame(runner1, runner2); 146 | 147 | // Verify server is running for the new runner 148 | this.AssertServerUpAndReady(runner2.ConnectionString); 149 | 150 | // Cleanup 151 | pool.Return(runner2); 152 | } 153 | 154 | [Fact] 155 | public void Return_Throws_When_Runner_Not_From_Pool() 156 | { 157 | // Arrange 158 | var options = CreateDefaultOptions(); 159 | using var pool = new MongoRunnerPool(options); 160 | using var externalRunner = MongoRunner.Run(options, testContextAccessor.Current.CancellationToken); 161 | 162 | // Act & Assert 163 | Assert.Throws(() => pool.Return(externalRunner)); 164 | } 165 | 166 | [Fact] 167 | public async Task Return_Disposes_Runner_When_MaxRentals_Reached() 168 | { 169 | // Arrange 170 | var options = CreateDefaultOptions(); 171 | using var pool = new MongoRunnerPool(options, 1); 172 | 173 | // Act 174 | var runner = await pool.RentAsync(testContextAccessor.Current.CancellationToken); 175 | var connectionString = runner.ConnectionString; 176 | 177 | // Verify the server is running before returning 178 | this.AssertServerUpAndReady(connectionString); 179 | 180 | // Return the runner - it will be marked for disposal because it reached max rentals (1) 181 | pool.Return(runner); 182 | 183 | // Rent again - should get a new runner since we've maxed rentals at 1 184 | var runner2 = await pool.RentAsync(testContextAccessor.Current.CancellationToken); 185 | 186 | // At this point, the original runner should be disposed 187 | // Trying to use it should throw a connection exception 188 | AssertServerDown(connectionString); 189 | 190 | // But the new runner should be working 191 | this.AssertServerUpAndReady(runner2.ConnectionString); 192 | 193 | // Cleanup 194 | pool.Return(runner2); 195 | } 196 | 197 | [Fact] 198 | public void Dispose_Disposes_All_Runners() 199 | { 200 | // Arrange 201 | var options = CreateDefaultOptions(); 202 | var pool = new MongoRunnerPool(options); 203 | 204 | // Act 205 | var runner1 = pool.Rent(testContextAccessor.Current.CancellationToken); 206 | var runner2 = pool.Rent(testContextAccessor.Current.CancellationToken); 207 | var connectionString1 = runner1.ConnectionString; 208 | var connectionString2 = runner2.ConnectionString; 209 | 210 | // Assert clients connect successfully before disposal 211 | this.AssertServerUpAndReady(connectionString1); 212 | this.AssertServerUpAndReady(connectionString2); 213 | 214 | // Dispose the pool without returning the runners 215 | pool.Dispose(); 216 | 217 | // Assert clients cannot connect anymore 218 | AssertServerDown(connectionString1); 219 | AssertServerDown(connectionString2); 220 | } 221 | 222 | [Fact] 223 | public async Task Rent_Throws_ObjectDisposedException_When_Disposed() 224 | { 225 | // Arrange 226 | var options = CreateDefaultOptions(); 227 | var pool = new MongoRunnerPool(options); 228 | pool.Dispose(); 229 | 230 | // Act & Assert 231 | await Assert.ThrowsAsync(() => 232 | pool.RentAsync(testContextAccessor.Current.CancellationToken)); 233 | Assert.Throws(() => pool.Rent(testContextAccessor.Current.CancellationToken)); 234 | } 235 | 236 | [Fact] 237 | public void Return_Throws_ObjectDisposedException_When_Disposed() 238 | { 239 | // Arrange 240 | var options = CreateDefaultOptions(); 241 | var pool = new MongoRunnerPool(options); 242 | var runner = pool.Rent(testContextAccessor.Current.CancellationToken); 243 | pool.Dispose(); 244 | 245 | // Act & Assert 246 | Assert.Throws(() => pool.Return(runner)); 247 | } 248 | 249 | [Theory] 250 | [InlineData(0)] 251 | [InlineData(-1)] 252 | public void Constructor_Throws_When_MaxRentalsPerRunner_LessThan_One(int maxRentals) 253 | { 254 | // Arrange 255 | var options = CreateDefaultOptions(); 256 | 257 | // Act & Assert 258 | Assert.Throws(() => new MongoRunnerPool(options, maxRentals)); 259 | } 260 | 261 | [Fact] 262 | public void Constructor_Throws_When_Options_Is_Null() 263 | { 264 | // Act & Assert 265 | Assert.Throws(() => new MongoRunnerPool(null!)); 266 | } 267 | 268 | [Fact] 269 | public void Pool_Creates_MaxRentalsPerRunner_Distinct_Instances() 270 | { 271 | // Arrange 272 | const int maxRentalsPerRunner = 25; 273 | const int totalRentals = 100; 274 | const int expectedDistinctInstances = 4; 275 | 276 | var options = CreateDefaultOptions(); 277 | using var pool = new MongoRunnerPool(options, maxRentalsPerRunner); 278 | var connectionStrings = new HashSet(StringComparer.Ordinal); 279 | 280 | // Act 281 | for (var i = 0; i < totalRentals; i++) 282 | { 283 | var runner = pool.Rent(testContextAccessor.Current.CancellationToken); 284 | connectionStrings.Add(runner.ConnectionString); 285 | } 286 | 287 | // Assert 288 | Assert.Equal(expectedDistinctInstances, connectionStrings.Count); 289 | } 290 | 291 | [Fact] 292 | public void PooledRunner_Dispose_DoesNothing_But_Return_DisposesWhenMaxed() 293 | { 294 | // Arrange 295 | var options = CreateDefaultOptions(); 296 | using var pool = new MongoRunnerPool(options, maxRentalsPerRunner: 2); 297 | var runner = pool.Rent(testContextAccessor.Current.CancellationToken); 298 | var connectionString = runner.ConnectionString; 299 | 300 | // Act 1: Dispose the pooled runner should have no effect 301 | runner.Dispose(); 302 | this.AssertServerUpAndReady(connectionString); 303 | 304 | // Act 2: Once returned and no more rentals 305 | pool.Return(runner); 306 | pool.Return(runner); 307 | 308 | // Assert 2: Server is no longer accessible 309 | AssertServerDown(connectionString); 310 | } 311 | 312 | private void AssertServerUpAndReady(string connectionString) 313 | { 314 | GetAdminDatabase(connectionString).RunCommand(new BsonDocument("ping", 1), cancellationToken: testContextAccessor.Current.CancellationToken); 315 | } 316 | 317 | private static void AssertServerDown(string connectionString) 318 | { 319 | var url = new MongoUrl(connectionString); 320 | 321 | TcpListener? listener = null; 322 | try 323 | { 324 | listener = new TcpListener(IPAddress.Loopback, url.Server.Port); 325 | listener.Start(); 326 | 327 | // As expected, the port is available, so the server is down 328 | } 329 | catch (SocketException ex) 330 | { 331 | Assert.Fail($"Server is still running on port {url.Server.Port}. Exception: {ex}"); 332 | } 333 | finally 334 | { 335 | listener?.Stop(); 336 | } 337 | } 338 | 339 | private static MongoRunnerOptions CreateDefaultOptions() => new(); 340 | 341 | private static IMongoDatabase GetAdminDatabase(string connectionString) 342 | { 343 | var clientSettings = MongoClientSettings.FromConnectionString(connectionString); 344 | return new MongoClient(clientSettings).GetDatabase("admin"); 345 | } 346 | } 347 | -------------------------------------------------------------------------------- /src/EphemeralMongo.Tests/MongoRunnerTests.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics.CodeAnalysis; 2 | using System.Net; 3 | using System.Net.Sockets; 4 | using System.Runtime.InteropServices; 5 | using System.Text.Json; 6 | using System.Text.Json.Serialization; 7 | using EphemeralMongo.Download; 8 | using MongoDB.Driver; 9 | 10 | namespace EphemeralMongo.Tests; 11 | 12 | public class MongoRunnerTests(ITestOutputHelper testOutputHelper, ITestContextAccessor testContextAccessor) 13 | { 14 | [Fact] 15 | public async Task StartMongo_WithNonExistentBinaryDirectory_ThrowsFileNotFoundException() 16 | { 17 | var options = new MongoRunnerOptions 18 | { 19 | StandardOutputLogger = this.MongoMessageLogger, 20 | StandardErrorLogger = this.MongoMessageLogger, 21 | BinaryDirectory = Guid.NewGuid().ToString(), 22 | AdditionalArguments = ["--quiet"], 23 | }; 24 | 25 | IMongoRunner? runner = null; 26 | 27 | try 28 | { 29 | var ex = await Assert.ThrowsAsync(async () => 30 | { 31 | runner = await MongoRunner.RunAsync(options, testContextAccessor.Current.CancellationToken); 32 | }); 33 | 34 | Assert.Contains(options.BinaryDirectory, ex.ToString()); 35 | Assert.DoesNotContain("runtimes", ex.ToString()); 36 | } 37 | finally 38 | { 39 | runner?.Dispose(); 40 | } 41 | } 42 | 43 | [Fact] 44 | [Trait(XunitConstants.Category, XunitConstants.SlowOnWindows)] 45 | public async Task StartMongo_WithTemporaryDataDirectory_CleansUpOldDirectories() 46 | { 47 | var rootDataDirectoryPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); 48 | 49 | try 50 | { 51 | var options = new MongoRunnerOptions 52 | { 53 | StandardOutputLogger = this.MongoMessageLogger, 54 | StandardErrorLogger = this.MongoMessageLogger, 55 | RootDataDirectoryPath = rootDataDirectoryPath, 56 | AdditionalArguments = ["--quiet"], 57 | }; 58 | 59 | testOutputHelper.WriteLine("Root data directory path: {0}", options.RootDataDirectoryPath); 60 | Assert.False(Directory.Exists(options.RootDataDirectoryPath), "The root data directory should not exist yet."); 61 | 62 | // Creating a first data directory 63 | using (await MongoRunner.RunAsync(options, testContextAccessor.Current.CancellationToken)) 64 | { 65 | } 66 | 67 | // Creating another data directory 68 | using (await MongoRunner.RunAsync(options, testContextAccessor.Current.CancellationToken)) 69 | { 70 | } 71 | 72 | // Assert there's now two data directories 73 | var dataDirectories = new HashSet(Directory.EnumerateDirectories(options.RootDataDirectoryPath), StringComparer.Ordinal); 74 | testOutputHelper.WriteLine("Data directories: {0}", string.Join(", ", dataDirectories)); 75 | Assert.Equal(2, dataDirectories.Count); 76 | 77 | // Shorten the lifetime of the data directories and wait for a longer time 78 | options.DataDirectoryLifetime = TimeSpan.FromSeconds(1); 79 | await Task.Delay(TimeSpan.FromSeconds(2), testContextAccessor.Current.CancellationToken); 80 | 81 | // This should delete the old data directories and create a new one 82 | using (await MongoRunner.RunAsync(options, testContextAccessor.Current.CancellationToken)) 83 | { 84 | } 85 | 86 | var dataDirectoriesAfterCleanup = new HashSet(Directory.EnumerateDirectories(options.RootDataDirectoryPath), StringComparer.Ordinal); 87 | testOutputHelper.WriteLine("Data directories after cleanup: {0}", string.Join(", ", dataDirectoriesAfterCleanup)); 88 | 89 | var thirdDataDirectory = Assert.Single(dataDirectoriesAfterCleanup); 90 | Assert.DoesNotContain(thirdDataDirectory, dataDirectories); 91 | } 92 | finally 93 | { 94 | try 95 | { 96 | Directory.Delete(rootDataDirectoryPath, recursive: true); 97 | } 98 | catch (DirectoryNotFoundException) 99 | { 100 | } 101 | } 102 | } 103 | 104 | [Theory] 105 | [Trait(XunitConstants.Category, XunitConstants.SlowOnWindows)] 106 | [InlineData(MongoEdition.Community, false)] 107 | [InlineData(MongoEdition.Enterprise, false)] 108 | [InlineData(MongoEdition.Community, true)] 109 | [InlineData(MongoEdition.Enterprise, true)] 110 | public async Task Mongo6Operations_ImportAndExport_SucceedsAcrossInstances(MongoEdition edition, bool replset) 111 | { 112 | await this.MongoOperations_ImportAndExport_SucceedsAcrossInstances(MongoVersion.V6, edition, replset); 113 | } 114 | 115 | [Theory] 116 | [Trait(XunitConstants.Category, XunitConstants.SlowOnWindows)] 117 | [InlineData(MongoEdition.Community, false)] 118 | [InlineData(MongoEdition.Enterprise, false)] 119 | [InlineData(MongoEdition.Community, true)] 120 | [InlineData(MongoEdition.Enterprise, true)] 121 | public async Task Mongo7Operations_ImportAndExport_SucceedsAcrossInstances(MongoEdition edition, bool replset) 122 | { 123 | await this.MongoOperations_ImportAndExport_SucceedsAcrossInstances(MongoVersion.V7, edition, replset); 124 | } 125 | 126 | [Theory] 127 | [InlineData(MongoEdition.Community, false)] 128 | [InlineData(MongoEdition.Enterprise, false)] 129 | [InlineData(MongoEdition.Community, true)] 130 | [InlineData(MongoEdition.Enterprise, true)] 131 | public async Task Mongo8Operations_ImportAndExport_SucceedsAcrossInstances(MongoEdition edition, bool replset) 132 | { 133 | await this.MongoOperations_ImportAndExport_SucceedsAcrossInstances(MongoVersion.V8, edition, replset); 134 | } 135 | 136 | private async Task MongoOperations_ImportAndExport_SucceedsAcrossInstances(MongoVersion version, MongoEdition edition, bool replset) 137 | { 138 | if (version is MongoVersion.V6 or MongoVersion.V7 && edition == MongoEdition.Enterprise && RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) 139 | { 140 | var target = DownloadTargetHelper.Instance.GetOriginalLinuxTarget(); 141 | if (target == "ubuntu2404") 142 | { 143 | Assert.Skip("Enterprise MongoDB 6 and 7 are not supported on Ubuntu 24.04"); 144 | } 145 | } 146 | 147 | const string databaseName = "default"; 148 | const string collectionName = "people"; 149 | 150 | var options = new MongoRunnerOptions 151 | { 152 | Version = version, 153 | Edition = edition, 154 | UseSingleNodeReplicaSet = replset, 155 | StandardOutputLogger = this.MongoMessageLogger, 156 | StandardErrorLogger = this.MongoMessageLogger, 157 | AdditionalArguments = edition == MongoEdition.Enterprise 158 | ? ["--quiet", "--storageEngine", "inMemory"] 159 | : ["--quiet"], 160 | }; 161 | 162 | using (var runner = await MongoRunner.RunAsync(options, testContextAccessor.Current.CancellationToken)) 163 | { 164 | if (replset) 165 | { 166 | Assert.Contains("replicaSet", runner.ConnectionString); 167 | } 168 | else 169 | { 170 | Assert.DoesNotContain("replicaSet", runner.ConnectionString); 171 | } 172 | } 173 | 174 | var originalPerson = new Person("john", "John Doe"); 175 | var exportedFilePath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); 176 | 177 | try 178 | { 179 | using (var runner1 = await MongoRunner.RunAsync(options, testContextAccessor.Current.CancellationToken)) 180 | { 181 | var database = new MongoClient(runner1.ConnectionString).GetDatabase(databaseName); 182 | 183 | // Verify that the collection is empty 184 | var personBeforeImport = database.GetCollection(collectionName).Find(FilterDefinition.Empty).FirstOrDefault(testContextAccessor.Current.CancellationToken); 185 | Assert.Null(personBeforeImport); 186 | 187 | // Add a document 188 | await database.GetCollection(collectionName).InsertOneAsync(new Person(originalPerson.Id, originalPerson.Name), options: null, cancellationToken: testContextAccessor.Current.CancellationToken); 189 | await runner1.ExportAsync(databaseName, collectionName, exportedFilePath, ["--jsonArray"], testContextAccessor.Current.CancellationToken); 190 | 191 | // Verify that the document was inserted successfully 192 | var personAfterImport = database.GetCollection(collectionName).Find(FilterDefinition.Empty).FirstOrDefault(testContextAccessor.Current.CancellationToken); 193 | Assert.Equal(originalPerson, personAfterImport); 194 | } 195 | 196 | #pragma warning disable CA1849 // We want to test synchronous methods 197 | IMongoRunner runner2; 198 | using (runner2 = MongoRunner.Run(options, testContextAccessor.Current.CancellationToken)) 199 | { 200 | var database = new MongoClient(runner2.ConnectionString).GetDatabase(databaseName); 201 | 202 | // Verify that the collection is empty 203 | var personBeforeImport = database.GetCollection(collectionName).Find(FilterDefinition.Empty).FirstOrDefault(testContextAccessor.Current.CancellationToken); 204 | Assert.Null(personBeforeImport); 205 | 206 | // Import the exported collection 207 | runner2.Import(databaseName, collectionName, exportedFilePath, ["--jsonArray"], drop: false, testContextAccessor.Current.CancellationToken); 208 | 209 | // Verify that the document was imported successfully 210 | var personAfterImport = database.GetCollection(collectionName).Find(FilterDefinition.Empty).FirstOrDefault(testContextAccessor.Current.CancellationToken); 211 | Assert.Equal(originalPerson, personAfterImport); 212 | } 213 | #pragma warning restore CA1849 214 | 215 | // Disposing twice does nothing 216 | runner2.Dispose(); 217 | 218 | // Can't use import or export if already disposed 219 | await Assert.ThrowsAsync(() => runner2.ExportAsync("whatever", "whatever", "whatever.json", cancellationToken: testContextAccessor.Current.CancellationToken)); 220 | await Assert.ThrowsAsync(() => runner2.ImportAsync("whatever", "whatever", "whatever.json", cancellationToken: testContextAccessor.Current.CancellationToken)); 221 | } 222 | finally 223 | { 224 | File.Delete(exportedFilePath); 225 | } 226 | } 227 | 228 | [Fact] 229 | public async Task StartMongo_WithInvalidArgument_ThrowsExceptionWithDetails() 230 | { 231 | var options = new MongoRunnerOptions 232 | { 233 | Version = MongoVersion.V8, 234 | StandardOutputLogger = this.MongoMessageLogger, 235 | StandardErrorLogger = this.MongoMessageLogger, 236 | AdditionalArguments = ["--invalid-argument"], 237 | }; 238 | 239 | var ex = await Assert.ThrowsAsync(async () => 240 | { 241 | using var _ = await MongoRunner.RunAsync(options, testContextAccessor.Current.CancellationToken); 242 | }); 243 | 244 | testOutputHelper.WriteLine(ex.Message); 245 | Assert.Contains("unrecognised option '--invalid-argument'", ex.Message); 246 | } 247 | 248 | [Fact] 249 | public async Task StartMongo_WithPortInUse_ThrowsExceptionWithDetails() 250 | { 251 | var listener = new TcpListener(IPAddress.Loopback, port: 0); 252 | 253 | try 254 | { 255 | listener.Start(); 256 | var port = ((IPEndPoint)listener.LocalEndpoint).Port; 257 | 258 | var options = new MongoRunnerOptions 259 | { 260 | Version = MongoVersion.V8, 261 | StandardOutputLogger = testOutputHelper.WriteLine, 262 | StandardErrorLogger = testOutputHelper.WriteLine, 263 | AdditionalArguments = ["--quiet"], 264 | MongoPort = port, 265 | }; 266 | 267 | var ex = await Assert.ThrowsAsync(async () => 268 | { 269 | using var _ = await MongoRunner.RunAsync(options, testContextAccessor.Current.CancellationToken); 270 | }); 271 | 272 | testOutputHelper.WriteLine(ex.Message); 273 | 274 | // Full message looks like this: 275 | // The MongoDB process '' exited unexpectedly with code 48. Output:{"t":{"$date":"2025-04-18T22:44:09.346-04:00"},"s":"E", "c":"CONTROL", "id":20568, "ctx":"initandlisten","msg":"Error setting up listener","attr":{"error":{"code":9001,"codeName":"SocketException","errmsg":"127.0.0.1:60912 :: caused by :: setup bind :: caused by :: An attempt was made to access a socket in a way forbidden by its access permissions."}}} 276 | Assert.Contains("SocketException", ex.Message); 277 | } 278 | finally 279 | { 280 | listener.Stop(); 281 | } 282 | } 283 | 284 | private void MongoMessageLogger(string message) 285 | { 286 | try 287 | { 288 | var trace = JsonSerializer.Deserialize(message); 289 | 290 | if (trace != null && !string.IsNullOrEmpty(trace.Message)) 291 | { 292 | // https://www.mongodb.com/docs/manual/reference/log-messages/#std-label-log-severity-levels 293 | var logLevel = trace.Severity switch 294 | { 295 | "F" => "CTR", 296 | "E" => "ERR", 297 | "W" => "WRN", 298 | _ => "INF", 299 | }; 300 | 301 | const int longestComponentNameLength = 8; 302 | testOutputHelper.WriteLine("{0} {1} {2}", logLevel, trace.Component.PadRight(longestComponentNameLength), trace.Message); 303 | return; 304 | } 305 | } 306 | catch (JsonException) 307 | { 308 | } 309 | 310 | testOutputHelper.WriteLine(message); 311 | } 312 | 313 | private sealed class MongoTrace 314 | { 315 | [JsonPropertyName("s")] 316 | public string Severity { get; set; } = string.Empty; 317 | 318 | [JsonPropertyName("c")] 319 | public string Component { get; set; } = string.Empty; 320 | 321 | [JsonPropertyName("msg")] 322 | public string Message { get; set; } = string.Empty; 323 | } 324 | 325 | private sealed record Person(string Id, string Name) 326 | { 327 | [SuppressMessage("ReSharper", "UnusedMember.Local", Justification = "Used by MongoDB deserialization")] 328 | public Person() 329 | : this(string.Empty, string.Empty) 330 | { 331 | } 332 | } 333 | } -------------------------------------------------------------------------------- /src/EphemeralMongo.Tests/ProcessArgumentTests.cs: -------------------------------------------------------------------------------- 1 | namespace EphemeralMongo.Tests; 2 | 3 | public class ProcessArgumentTests 4 | { 5 | [Theory] 6 | [InlineData("", "\"\"")] 7 | [InlineData("/", "/")] 8 | [InlineData("\\", "\\")] 9 | [InlineData("foo", "foo")] 10 | [InlineData("/foo", "/foo")] 11 | [InlineData("c:\\foo", "c:\\foo")] 12 | [InlineData("\\foo", "\\foo")] 13 | [InlineData("foo bar", "\"foo bar\"")] 14 | [InlineData("/foo/hello world", "\"/foo/hello world\"")] 15 | [InlineData("c:\\foo\\hello world", "\"c:\\foo\\hello world\"")] 16 | [InlineData("\\\"", "\"\\\\\\\"\"")] 17 | [InlineData("fo\"ob\"a \\\\r", "\"fo\\\"ob\\\"a \\\\r\"")] 18 | public void Nothing(string inputPath, string expectedEscapedPath) 19 | { 20 | Assert.Equal(expectedEscapedPath, ProcessArgument.Escape(inputPath)); 21 | } 22 | } -------------------------------------------------------------------------------- /src/EphemeralMongo.Tests/XunitConstants.cs: -------------------------------------------------------------------------------- 1 | namespace EphemeralMongo.Tests; 2 | 3 | internal sealed class XunitConstants 4 | { 5 | public const string Category = nameof(Category); 6 | 7 | // Tests on GitHub Actions with the Windows runner are 4x slower than on Linux 8 | public const string SlowOnWindows = nameof(SlowOnWindows); 9 | } -------------------------------------------------------------------------------- /src/EphemeralMongo.Tests/xunit.runner.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://xunit.net/schema/current/xunit.runner.schema.json" 3 | } 4 | -------------------------------------------------------------------------------- /src/EphemeralMongo.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EphemeralMongo.v2.Tests", "EphemeralMongo.v2.Tests\EphemeralMongo.v2.Tests.csproj", "{F33F8D0A-B3F1-4471-8DD7-937CFAC005E5}" 4 | EndProject 5 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "files", "files", "{5C8A04E9-E805-451A-B73B-05248DCCD0EE}" 6 | ProjectSection(SolutionItems) = preProject 7 | ..\README.md = ..\README.md 8 | ..\global.json = ..\global.json 9 | ..\nuget.config = ..\nuget.config 10 | ..\.editorconfig = ..\.editorconfig 11 | ..\Directory.Build.props = ..\Directory.Build.props 12 | ..\Directory.Packages.props = ..\Directory.Packages.props 13 | ..\build.ps1 = ..\build.ps1 14 | EndProjectSection 15 | EndProject 16 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EphemeralMongo.v2", "EphemeralMongo.v2\EphemeralMongo.v2.csproj", "{E58299B0-E5C5-4358-ACA2-11AA859EAD81}" 17 | EndProject 18 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EphemeralMongo", "EphemeralMongo\EphemeralMongo.csproj", "{0CA8AB33-9DF9-473E-ACB6-41C369E524F3}" 19 | EndProject 20 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EphemeralMongo.Tests", "EphemeralMongo.Tests\EphemeralMongo.Tests.csproj", "{A365BA82-91A2-4E5E-BDA1-803C9BF170A1}" 21 | EndProject 22 | Global 23 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 24 | Debug|Any CPU = Debug|Any CPU 25 | Release|Any CPU = Release|Any CPU 26 | EndGlobalSection 27 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 28 | {F33F8D0A-B3F1-4471-8DD7-937CFAC005E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {F33F8D0A-B3F1-4471-8DD7-937CFAC005E5}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {F33F8D0A-B3F1-4471-8DD7-937CFAC005E5}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {F33F8D0A-B3F1-4471-8DD7-937CFAC005E5}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {E58299B0-E5C5-4358-ACA2-11AA859EAD81}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {E58299B0-E5C5-4358-ACA2-11AA859EAD81}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {E58299B0-E5C5-4358-ACA2-11AA859EAD81}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {E58299B0-E5C5-4358-ACA2-11AA859EAD81}.Release|Any CPU.Build.0 = Release|Any CPU 36 | {0CA8AB33-9DF9-473E-ACB6-41C369E524F3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 37 | {0CA8AB33-9DF9-473E-ACB6-41C369E524F3}.Debug|Any CPU.Build.0 = Debug|Any CPU 38 | {0CA8AB33-9DF9-473E-ACB6-41C369E524F3}.Release|Any CPU.ActiveCfg = Release|Any CPU 39 | {0CA8AB33-9DF9-473E-ACB6-41C369E524F3}.Release|Any CPU.Build.0 = Release|Any CPU 40 | {A365BA82-91A2-4E5E-BDA1-803C9BF170A1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 41 | {A365BA82-91A2-4E5E-BDA1-803C9BF170A1}.Debug|Any CPU.Build.0 = Debug|Any CPU 42 | {A365BA82-91A2-4E5E-BDA1-803C9BF170A1}.Release|Any CPU.ActiveCfg = Release|Any CPU 43 | {A365BA82-91A2-4E5E-BDA1-803C9BF170A1}.Release|Any CPU.Build.0 = Release|Any CPU 44 | EndGlobalSection 45 | GlobalSection(NestedProjects) = preSolution 46 | EndGlobalSection 47 | EndGlobal 48 | -------------------------------------------------------------------------------- /src/EphemeralMongo.v2.Tests/EphemeralMongo.v2.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net472;net9.0 4 | net9.0 5 | Exe 6 | enable 7 | enable 8 | false 9 | $(NoWarn);CA2007 10 | true 11 | true 12 | EphemeralMongo.Tests 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /src/EphemeralMongo.v2/EphemeralMongo.v2.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | netstandard2.0;net8.0 4 | EphemeralMongo 5 | EphemeralMongo 6 | EphemeralMongo.v2 7 | true 8 | Provides access to preconfigured MongoDB servers for testing purposes, without Docker or other dependencies. 9 | README.md 10 | true 11 | $(DefineConstants);MONGODB_V2 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | all 29 | runtime; build; native; contentfiles; analyzers 30 | 31 | 32 | all 33 | runtime; build; native; contentfiles; analyzers 34 | 35 | 36 | all 37 | runtime; build; native; contentfiles; analyzers 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /src/EphemeralMongo/BaseMongoProcess.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | using System.Text; 3 | 4 | namespace EphemeralMongo; 5 | 6 | internal abstract class BaseMongoProcess : IMongoProcess 7 | { 8 | protected BaseMongoProcess(MongoRunnerOptions options, string executablePath, string[] arguments) 9 | { 10 | this.Options = options; 11 | 12 | NativeMethods.EnsureMongoProcessesAreKilledWhenCurrentProcessIsKilled(); 13 | 14 | var processStartInfo = new ProcessStartInfo 15 | { 16 | FileName = executablePath, 17 | Arguments = string.Join(" ", arguments), 18 | CreateNoWindow = true, 19 | UseShellExecute = false, 20 | RedirectStandardOutput = true, 21 | RedirectStandardError = true, 22 | StandardOutputEncoding = Encoding.UTF8, 23 | StandardErrorEncoding = Encoding.UTF8, 24 | }; 25 | 26 | this.Process = new Process 27 | { 28 | StartInfo = processStartInfo, 29 | EnableRaisingEvents = true, 30 | }; 31 | 32 | this.Process.OutputDataReceived += this.OnOutputDataReceivedForLogging; 33 | this.Process.ErrorDataReceived += this.OnErrorDataReceivedForLogging; 34 | } 35 | 36 | protected MongoRunnerOptions Options { get; } 37 | 38 | protected Process Process { get; } 39 | 40 | private void OnOutputDataReceivedForLogging(object sender, DataReceivedEventArgs args) 41 | { 42 | if (this.Options.StandardOutputLogger != null && args.Data != null) 43 | { 44 | this.Options.StandardOutputLogger(args.Data); 45 | } 46 | } 47 | 48 | private void OnErrorDataReceivedForLogging(object sender, DataReceivedEventArgs args) 49 | { 50 | if (this.Options.StandardErrorLogger != null && args.Data != null) 51 | { 52 | this.Options.StandardErrorLogger(args.Data); 53 | } 54 | } 55 | 56 | public abstract Task StartAsync(CancellationToken cancellationToken); 57 | 58 | public void Dispose() 59 | { 60 | this.Process.OutputDataReceived -= this.OnOutputDataReceivedForLogging; 61 | this.Process.ErrorDataReceived -= this.OnErrorDataReceivedForLogging; 62 | 63 | this.Process.CancelOutputRead(); 64 | this.Process.CancelErrorRead(); 65 | 66 | if (!this.Process.HasExited) 67 | { 68 | try 69 | { 70 | this.Process.Kill(); 71 | this.Process.WaitForExit(); 72 | } 73 | catch 74 | { 75 | // ignored, we did our best to stop the process 76 | } 77 | } 78 | 79 | this.Process.Dispose(); 80 | } 81 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/Download/DownloadArchitectureHelper.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.InteropServices; 2 | 3 | namespace EphemeralMongo.Download; 4 | 5 | internal static class DownloadArchitectureHelper 6 | { 7 | public static string GetArchitecture() 8 | { 9 | return GetArchitecture(RuntimeInformation.ProcessArchitecture, RuntimeInformationHelper.OSPlatform); 10 | } 11 | 12 | public static string GetArchitecture(Architecture architecture, OSPlatform platform) 13 | { 14 | return architecture switch 15 | { 16 | Architecture.X86 or Architecture.X64 => "x86_64", 17 | 18 | // "arm64" seems to be returned only for macOS releases for both mongod and tools 19 | Architecture.Arm64 => platform == OSPlatform.OSX ? "arm64" : "aarch64", 20 | 21 | _ => throw new PlatformNotSupportedException($"Unsupported architecture {architecture}") 22 | }; 23 | } 24 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/Download/DownloadEditionHelper.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.InteropServices; 2 | 3 | namespace EphemeralMongo.Download; 4 | 5 | internal static class DownloadEditionHelper 6 | { 7 | public static string GetEdition(MongoEdition edition) 8 | { 9 | return GetEdition(edition, RuntimeInformationHelper.OSPlatform); 10 | } 11 | 12 | public static string GetEdition(MongoEdition edition, OSPlatform platform) 13 | { 14 | if (edition == MongoEdition.Enterprise) 15 | { 16 | return "enterprise"; 17 | } 18 | 19 | return platform == OSPlatform.Linux ? "targeted" : "base"; 20 | } 21 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/Download/DownloadTargetHelper.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.InteropServices; 2 | using System.Text.RegularExpressions; 3 | 4 | namespace EphemeralMongo.Download; 5 | 6 | internal sealed class DownloadTargetHelper(string linuxOsReleasePath) 7 | { 8 | internal static readonly DownloadTargetHelper Instance = new DownloadTargetHelper("/etc/os-release"); 9 | 10 | public static string GetTarget(MongoVersion version) 11 | { 12 | return Instance.GetTarget(RuntimeInformationHelper.OSPlatform, version); 13 | } 14 | 15 | public string GetTarget(OSPlatform platform, MongoVersion version) 16 | { 17 | if (platform == OSPlatform.Windows) 18 | { 19 | return "windows"; 20 | } 21 | 22 | if (platform == OSPlatform.OSX) 23 | { 24 | return "macos"; 25 | } 26 | 27 | if (platform == OSPlatform.Linux) 28 | { 29 | return this.GetAdjustedLinuxTarget(version); 30 | } 31 | 32 | throw new PlatformNotSupportedException($"Unsupported operating system {RuntimeInformation.OSDescription}"); 33 | } 34 | 35 | private string GetAdjustedLinuxTarget(MongoVersion version) 36 | { 37 | // Some Linux distributions have limited support for older MongoDB versions. 38 | // For instance, there's no specific MongoDB binaries targeting Ubuntu 24.04 for MongoDB 7 and earlier, 39 | // but it works if use the Ubuntu 22.04 binaries on Ubuntu 24.04. 40 | // We're focusing on Ubuntu for now as it's the most common Linux distribution for CIs. 41 | var originalTarget = this.GetOriginalLinuxTarget(); 42 | 43 | if (originalTarget == "ubuntu2404" && version is MongoVersion.V6 or MongoVersion.V7) 44 | { 45 | return "ubuntu2204"; 46 | } 47 | 48 | return originalTarget; 49 | } 50 | 51 | // Matches ID and VERSION_ID keys and their values without quotes in /etc/os-release 52 | private static readonly Regex LinuxOsReleaseKeyValueRegex = new Regex( 53 | "^(?ID|VERSION_ID)=\"?(?[^\"]+)\"?$", 54 | RegexOptions.IgnoreCase | RegexOptions.Singleline); 55 | 56 | internal string GetOriginalLinuxTarget() 57 | { 58 | string? target = null; 59 | try 60 | { 61 | string? id = null; 62 | string? versionId = null; 63 | 64 | foreach (var line in File.ReadAllLines(linuxOsReleasePath)) 65 | { 66 | if (LinuxOsReleaseKeyValueRegex.Match(line) is { Success: true } match) 67 | { 68 | var key = match.Groups["key"].Value; 69 | var value = match.Groups["value"].Value; 70 | 71 | if (key.Equals("ID", StringComparison.OrdinalIgnoreCase)) 72 | { 73 | id = value; 74 | } 75 | else if (key.Equals("VERSION_ID", StringComparison.OrdinalIgnoreCase)) 76 | { 77 | versionId = value; 78 | } 79 | 80 | if (id != null && versionId != null) 81 | { 82 | target = GetLinuxTargetFromOsRelease(id, versionId); 83 | } 84 | } 85 | } 86 | } 87 | catch (IOException) 88 | { 89 | // We'll use the fallback target 90 | } 91 | 92 | const string fallbackTarget = "ubuntu2204"; 93 | return target ?? fallbackTarget; 94 | } 95 | 96 | // Written using https://downloads.mongodb.org/current.json from 2025-04-05 97 | // Backup available here: https://gist.github.com/asimmon/60e49484832e985a1d51a672e2d3e028 98 | // Used Docker to access the possible values in /etc/os-release 99 | // Ex: docker run --rm ubuntu:24.04 cat /etc/os-release 100 | private static string? GetLinuxTargetFromOsRelease(string id, string versionId) 101 | { 102 | if ("ubuntu".Equals(id, StringComparison.OrdinalIgnoreCase)) 103 | { 104 | return GetUbuntuTarget(versionId); 105 | } 106 | 107 | if ("debian".Equals(id, StringComparison.OrdinalIgnoreCase)) 108 | { 109 | return GetDebianTarget(versionId); 110 | } 111 | 112 | // ID like opensuse-leap or opensuse-tumbleweed (https://hub.docker.com/_/opensuse) 113 | if (id.StartsWith("opensuse", StringComparison.OrdinalIgnoreCase)) 114 | { 115 | return GetOpenSuseTarget(versionId); 116 | } 117 | 118 | if ("rhel".Equals(id, StringComparison.OrdinalIgnoreCase)) 119 | { 120 | return GetRedHatEnterpriseLinuxTarget(versionId); 121 | } 122 | 123 | // Amazon Linux (https://hub.docker.com/_/amazonlinux) 124 | if ("amzn".Equals(id, StringComparison.OrdinalIgnoreCase)) 125 | { 126 | return GetAmazonLinuxTarget(versionId); 127 | } 128 | 129 | return null; 130 | } 131 | 132 | private static string GetUbuntuTarget(string versionId) 133 | { 134 | string? target = null; 135 | 136 | if (Version.TryParse(EnsureAtLeastTwoVersionParts(versionId), out var version)) 137 | { 138 | target = version.Major switch 139 | { 140 | >= 24 => "ubuntu2404", 141 | >= 22 => "ubuntu2204", 142 | >= 20 => "ubuntu2004", 143 | >= 18 => "ubuntu1804", 144 | _ => null 145 | }; 146 | } 147 | 148 | return target ?? throw new NotSupportedException($"Unsupported Ubuntu version {versionId}"); 149 | } 150 | 151 | private static string GetDebianTarget(string versionId) 152 | { 153 | string? target = null; 154 | 155 | if (Version.TryParse(EnsureAtLeastTwoVersionParts(versionId), out var version)) 156 | { 157 | target = version.Major switch 158 | { 159 | >= 12 => "debian12", 160 | >= 11 => "debian11", 161 | >= 10 => "debian10", 162 | _ => null 163 | }; 164 | } 165 | 166 | return target ?? throw new NotSupportedException($"Unsupported Debian version {versionId}"); 167 | } 168 | 169 | private static string GetOpenSuseTarget(string versionId) 170 | { 171 | string? target = null; 172 | if (Version.TryParse(EnsureAtLeastTwoVersionParts(versionId), out var version)) 173 | { 174 | target = version.Major switch 175 | { 176 | >= 15 => "suse15", 177 | >= 12 => "suse12", 178 | _ => null 179 | }; 180 | } 181 | 182 | return target ?? throw new NotSupportedException($"Unsupported OpenSUSE version {versionId}"); 183 | } 184 | 185 | private static string GetRedHatEnterpriseLinuxTarget(string versionId) 186 | { 187 | if (Version.TryParse(EnsureAtLeastTwoVersionParts(versionId), out var version)) 188 | { 189 | if (version >= new Version(9, 3)) 190 | { 191 | return "rhel93"; 192 | } 193 | 194 | if (version >= new Version(9, 0)) 195 | { 196 | return "rhel90"; 197 | } 198 | 199 | if (version >= new Version(8, 3)) 200 | { 201 | return "rhel83"; 202 | } 203 | 204 | if (version >= new Version(8, 1)) 205 | { 206 | return "rhel81"; 207 | } 208 | 209 | if (version >= new Version(8, 0)) 210 | { 211 | return "rhel8"; 212 | } 213 | 214 | if (version >= new Version(7, 2)) 215 | { 216 | return "rhel72"; 217 | } 218 | 219 | if (version >= new Version(7, 0)) 220 | { 221 | return "rhel70"; 222 | } 223 | } 224 | 225 | throw new NotSupportedException($"Unsupported Red Hat Enterprise Linux version {version}"); 226 | } 227 | 228 | private static string GetAmazonLinuxTarget(string versionId) => versionId switch 229 | { 230 | "2023" => "amazon2023", 231 | "2" => "amazon2", 232 | _ => throw new NotSupportedException($"Unsupported Amazon Linux version {versionId}") 233 | }; 234 | 235 | private static string EnsureAtLeastTwoVersionParts(string version) 236 | { 237 | // System.Version requires at least two parts (e.g., 18.04) 238 | #if NETSTANDARD2_0 239 | return version.IndexOf(".", StringComparison.Ordinal) == -1 ? $"{version}.0" : version; 240 | #else 241 | return version.Contains('.', StringComparison.Ordinal) ? version : $"{version}.0"; 242 | #endif 243 | } 244 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/Download/FileCompressionHelper.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | using System.IO.Compression; 3 | 4 | namespace EphemeralMongo.Download; 5 | 6 | internal static class FileCompressionHelper 7 | { 8 | public static async Task ExtractToDirectoryAsync(string archiveFilePath, string destinationDirectoryPath, CancellationToken cancellationToken) 9 | { 10 | if (archiveFilePath.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) 11 | { 12 | await ExtractZipToDirectoryAsync(archiveFilePath, destinationDirectoryPath, cancellationToken).ConfigureAwait(false); 13 | } 14 | else if (archiveFilePath.EndsWith(".tgz", StringComparison.OrdinalIgnoreCase)) 15 | { 16 | await ExtractTarGzToDirectoryAsync(archiveFilePath, destinationDirectoryPath, cancellationToken).ConfigureAwait(false); 17 | } 18 | else 19 | { 20 | throw new NotSupportedException($"The archive file format is not supported: {archiveFilePath}"); 21 | } 22 | } 23 | 24 | private static Task ExtractZipToDirectoryAsync(string archiveFilePath, string destinationDirectory, CancellationToken cancellationToken) 25 | { 26 | try 27 | { 28 | ZipFile.ExtractToDirectory(archiveFilePath, destinationDirectory); 29 | return Task.CompletedTask; 30 | } 31 | catch (Exception ex) 32 | { 33 | throw new EphemeralMongoException($"Failed to extract zip file {archiveFilePath} to {destinationDirectory}", ex); 34 | } 35 | } 36 | 37 | private static async Task ExtractTarGzToDirectoryAsync(string archiveFilePath, string destinationDirectory, CancellationToken cancellationToken) 38 | { 39 | var processStartInfo = new ProcessStartInfo 40 | { 41 | FileName = "tar", 42 | Arguments = $"-xzf {ProcessArgument.Escape(archiveFilePath)} -C {ProcessArgument.Escape(destinationDirectory)}", 43 | RedirectStandardOutput = true, 44 | RedirectStandardError = true, 45 | UseShellExecute = false, 46 | CreateNoWindow = true 47 | }; 48 | 49 | if (Process.Start(processStartInfo) is not { } process) 50 | { 51 | throw new EphemeralMongoException($"Failed to start the tar process to extract {archiveFilePath} to {destinationDirectory}"); 52 | } 53 | 54 | try 55 | { 56 | using (process) 57 | { 58 | process.EnableRaisingEvents = true; 59 | 60 | var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); 61 | 62 | void OnProcessExited(object? sender, EventArgs args) 63 | { 64 | var exitCode = process.ExitCode; 65 | if (exitCode == 0) 66 | { 67 | tcs.SetResult(true); 68 | } 69 | else 70 | { 71 | tcs.SetException(new InvalidOperationException($"The tar process exited with code {exitCode}")); 72 | } 73 | } 74 | 75 | process.Exited += OnProcessExited; 76 | 77 | try 78 | { 79 | using (cancellationToken.Register(() => tcs.TrySetCanceled(cancellationToken))) 80 | { 81 | await tcs.Task.ConfigureAwait(false); 82 | } 83 | } 84 | finally 85 | { 86 | process.Exited -= OnProcessExited; 87 | process.Kill(); 88 | #if NET8_0_OR_GREATER 89 | await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false); 90 | #else 91 | process.WaitForExit(); 92 | #endif 93 | } 94 | } 95 | } 96 | catch (Exception ex) 97 | { 98 | throw new EphemeralMongoException($"Failed to extract tar.gz file {archiveFilePath} to {destinationDirectory}", ex); 99 | } 100 | } 101 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/Download/FileHashHelper.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Cryptography; 2 | 3 | namespace EphemeralMongo.Download; 4 | 5 | internal static class FileHashHelper 6 | { 7 | #if NETSTANDARD2_0 8 | public static Task EnsureFileSha256HashAsync(string filePath, string expectedHash, CancellationToken cancellationToken) 9 | #else 10 | public static async Task EnsureFileSha256HashAsync(string filePath, string expectedHash, CancellationToken cancellationToken) 11 | #endif 12 | { 13 | string hash; 14 | 15 | try 16 | { 17 | Stream fileStream; 18 | #if NETSTANDARD2_0 19 | using (fileStream = File.OpenRead(filePath)) 20 | #else 21 | await using ((fileStream = File.OpenRead(filePath)).ConfigureAwait(false)) 22 | #endif 23 | { 24 | using var hasher = SHA256.Create(); 25 | #if NET8_0_OR_GREATER 26 | var hashBytes = await hasher.ComputeHashAsync(fileStream, cancellationToken).ConfigureAwait(false); 27 | hash = Convert.ToHexString(hashBytes); 28 | #else 29 | var hashBytes = hasher.ComputeHash(fileStream); 30 | hash = BitConverter.ToString(hashBytes).Replace("-", string.Empty); 31 | #endif 32 | } 33 | } 34 | catch (Exception ex) 35 | { 36 | throw new EphemeralMongoException($"Failed to compute SHA256 hash for file {filePath}", ex); 37 | } 38 | 39 | if (!hash.Equals(expectedHash, StringComparison.OrdinalIgnoreCase)) 40 | { 41 | throw new EphemeralMongoException($"The hash of the downloaded file {filePath} does not match the expected hash. Expected: {expectedHash}, Actual: {hash}"); 42 | } 43 | 44 | #if NETSTANDARD2_0 45 | return Task.CompletedTask; 46 | #endif 47 | } 48 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/Download/MongoArchiveDto.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace EphemeralMongo.Download; 4 | 5 | internal sealed class MongoArchiveDto 6 | { 7 | [JsonPropertyName("url")] 8 | public string Url { get; set; } = string.Empty; 9 | 10 | [JsonPropertyName("sha256")] 11 | public string Sha256 { get; set; } = string.Empty; 12 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/Download/MongoDownloadDto.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace EphemeralMongo.Download; 4 | 5 | internal sealed class MongoDownloadDto 6 | { 7 | [JsonPropertyName("arch")] 8 | public string Architecture { get; set; } = string.Empty; 9 | 10 | [JsonPropertyName("edition")] 11 | public string Edition { get; set; } = string.Empty; 12 | 13 | [JsonPropertyName("target")] 14 | public string Target { get; set; } = string.Empty; 15 | 16 | [JsonPropertyName("archive")] 17 | public MongoArchiveDto Archive { get; set; } = new MongoArchiveDto(); 18 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/Download/MongoExecutableDownloader.cs: -------------------------------------------------------------------------------- 1 | using System.Globalization; 2 | using System.Runtime.InteropServices; 3 | 4 | namespace EphemeralMongo.Download; 5 | 6 | internal static class MongoExecutableDownloader 7 | { 8 | private const string MongodExeFileNameWithoutExt = "mongod"; 9 | private const string MongoImportExeFileNameWithoutExt = "mongoimport"; 10 | private const string MongoExportExeFileNameWithoutExt = "mongoexport"; 11 | private const string LastCheckFileName = "last-check.txt"; 12 | 13 | private static readonly string MongodExeFileName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? MongodExeFileNameWithoutExt + ".exe" : MongodExeFileNameWithoutExt; 14 | private static readonly string MongoImportExeFileName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? MongoImportExeFileNameWithoutExt + ".exe" : MongoImportExeFileNameWithoutExt; 15 | private static readonly string MongoExportExeFileName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? MongoExportExeFileNameWithoutExt + ".exe" : MongoExportExeFileNameWithoutExt; 16 | 17 | private static readonly string AppDataDirPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ephemeral-mongo"); 18 | private static readonly string TmpDirPath = Path.Combine(Path.GetTempPath(), "ephemeral-mongo"); 19 | 20 | // The epoch for file time is 1/1/1601 12:00:00 AM 21 | // This value is returned by File.GetLastWriteTimeUtc when the file does not exist 22 | private static readonly DateTime FileTimeEpochUtc = DateTime.FromFileTimeUtc(0); 23 | 24 | private static readonly NamedMutex SharedMutex = new NamedMutex(); 25 | 26 | public static async Task DownloadMongodAsync(MongoRunnerOptions options, CancellationToken cancellationToken) 27 | { 28 | var majorVersion = (int)options.Version; 29 | var edition = DownloadEditionHelper.GetEdition(options.Edition); 30 | var architecture = DownloadArchitectureHelper.GetArchitecture(); 31 | var target = DownloadTargetHelper.GetTarget(options.Version); 32 | 33 | var baseExeDirName = string.Format(CultureInfo.InvariantCulture, "{0}-{1}-{2}", MongodExeFileNameWithoutExt, edition, majorVersion); 34 | var baseExeDirPath = Path.Combine(AppDataDirPath, "bin", MongodExeFileNameWithoutExt, baseExeDirName); 35 | Directory.CreateDirectory(baseExeDirPath); 36 | 37 | var lastCheckFilePath = Path.Combine(baseExeDirPath, LastCheckFileName); 38 | var lastCheckDateUtc = File.GetLastWriteTimeUtc(lastCheckFilePath); 39 | 40 | var skipNewExeVersionCheck = lastCheckDateUtc > FileTimeEpochUtc && DateTime.UtcNow - lastCheckDateUtc < options.NewVersionCheckTimeout; 41 | if (skipNewExeVersionCheck) 42 | { 43 | var existingExeFilePath = FindLatestExistingMongodExeFilePath(baseExeDirPath); 44 | if (existingExeFilePath != null) 45 | { 46 | return existingExeFilePath; 47 | } 48 | } 49 | 50 | await SharedMutex.WaitAsync(baseExeDirName, cancellationToken).ConfigureAwait(false); 51 | 52 | try 53 | { 54 | if (skipNewExeVersionCheck) 55 | { 56 | var existingExeFilePath = FindLatestExistingMongodExeFilePath(baseExeDirPath); 57 | if (existingExeFilePath != null) 58 | { 59 | return existingExeFilePath; 60 | } 61 | } 62 | 63 | var mongodVersions = await options.Transport.GetFromJsonAsync("https://downloads.mongodb.org/current.json", cancellationToken).ConfigureAwait(false); 64 | 65 | var mongodVersion = mongodVersions.Versions.FirstOrDefault(x => x.ProductionRelease && x.Version.StartsWith(majorVersion.ToString(CultureInfo.InvariantCulture), StringComparison.Ordinal)) 66 | ?? throw new EphemeralMongoException($"Could not find a production release for MongoDB major version {majorVersion}"); 67 | 68 | var mongodDownload = mongodVersion.Downloads.SingleOrDefault(x => x.Architecture == architecture && x.Edition == edition && x.Target == target) 69 | ?? throw new EphemeralMongoException($"Could not find a production release for MongoDB architecture {architecture}, edition {edition}, and target {target}"); 70 | 71 | var exeDirPath = Path.Combine(baseExeDirPath, mongodVersion.Version); 72 | var exeFilePath = Path.Combine(exeDirPath, MongodExeFileName); 73 | 74 | if (File.Exists(exeFilePath)) 75 | { 76 | await UpdateLastCheckFileAsync(lastCheckFilePath).ConfigureAwait(false); 77 | return exeFilePath; 78 | } 79 | 80 | var tmpDirName = $"{MongodExeFileNameWithoutExt}-{edition}-{mongodVersion.Version}-{Path.GetRandomFileName()}"; 81 | var tmpDownloadDirPath = Path.Combine(TmpDirPath, "downloads", tmpDirName); 82 | var tmpUncompressDirPath = Path.Combine(TmpDirPath, "uncompress", tmpDirName); 83 | 84 | Directory.CreateDirectory(tmpDownloadDirPath); 85 | Directory.CreateDirectory(tmpUncompressDirPath); 86 | 87 | var tmpDownloadFilePath = Path.Combine(tmpDownloadDirPath, Path.GetFileName(mongodDownload.Archive.Url)); 88 | 89 | try 90 | { 91 | await options.Transport.DownloadFileAsync(mongodDownload.Archive.Url, tmpDownloadFilePath, cancellationToken).ConfigureAwait(false); 92 | await FileHashHelper.EnsureFileSha256HashAsync(tmpDownloadFilePath, mongodDownload.Archive.Sha256, cancellationToken).ConfigureAwait(false); 93 | await FileCompressionHelper.ExtractToDirectoryAsync(tmpDownloadFilePath, tmpUncompressDirPath, cancellationToken).ConfigureAwait(false); 94 | 95 | var tmpUncompressedFirstDirPath = Directory.GetDirectories(tmpUncompressDirPath); 96 | if (tmpUncompressedFirstDirPath.Length != 1) 97 | { 98 | throw new EphemeralMongoException($"There should be only one directory in {tmpUncompressDirPath}, but found {tmpUncompressedFirstDirPath.Length}"); 99 | } 100 | 101 | var tmpExeDirPath = Path.Combine(tmpUncompressedFirstDirPath[0], "bin"); 102 | var tmpExeFilePath = Path.Combine(tmpExeDirPath, MongodExeFileName); 103 | if (!File.Exists(tmpExeFilePath)) 104 | { 105 | throw new EphemeralMongoException($"The executable file {tmpExeFilePath} could not be copied to {exeFilePath} because it does not exist"); 106 | } 107 | 108 | Directory.CreateDirectory(exeDirPath); 109 | 110 | SafeFileCopy(tmpExeFilePath, exeFilePath); 111 | 112 | if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) 113 | { 114 | // On Windows only as of 2025-04-08, the enterprise edition requires additional DLLs 115 | foreach (var tmpDllFilePath in Directory.EnumerateFiles(tmpExeDirPath, "*.dll", SearchOption.TopDirectoryOnly)) 116 | { 117 | var dllFilePath = Path.Combine(exeDirPath, Path.GetFileName(tmpDllFilePath)); 118 | SafeFileCopy(tmpDllFilePath, dllFilePath); 119 | } 120 | } 121 | 122 | await UpdateLastCheckFileAsync(lastCheckFilePath).ConfigureAwait(false); 123 | return exeFilePath; 124 | } 125 | finally 126 | { 127 | DeleteQuietly(tmpDownloadDirPath); 128 | DeleteQuietly(tmpUncompressDirPath); 129 | } 130 | } 131 | finally 132 | { 133 | SharedMutex.Release(baseExeDirName); 134 | } 135 | } 136 | 137 | public static async Task<(string MongoImportExePath, string MongoExportExePath)> DownloadMongoToolsAsync(MongoRunnerOptions options, CancellationToken cancellationToken) 138 | { 139 | const string baseExeDirName = "tools"; 140 | 141 | var baseExeDirPath = Path.Combine(AppDataDirPath, "bin", baseExeDirName); 142 | Directory.CreateDirectory(baseExeDirPath); 143 | 144 | var lastCheckFilePath = Path.Combine(baseExeDirPath, LastCheckFileName); 145 | var lastCheckDateUtc = File.GetLastWriteTimeUtc(lastCheckFilePath); 146 | 147 | var skipNewExeVersionCheck = lastCheckDateUtc > FileTimeEpochUtc && DateTime.UtcNow - lastCheckDateUtc < options.NewVersionCheckTimeout; 148 | if (skipNewExeVersionCheck) 149 | { 150 | var existingExeFilePath = FindLatestExistingToolExeFilePaths(baseExeDirPath); 151 | if (existingExeFilePath.HasValue) 152 | { 153 | return existingExeFilePath.Value; 154 | } 155 | } 156 | 157 | await SharedMutex.WaitAsync(baseExeDirName, cancellationToken).ConfigureAwait(false); 158 | 159 | try 160 | { 161 | if (skipNewExeVersionCheck) 162 | { 163 | var existingExeFilePath = FindLatestExistingToolExeFilePaths(baseExeDirPath); 164 | if (existingExeFilePath.HasValue) 165 | { 166 | return existingExeFilePath.Value; 167 | } 168 | } 169 | 170 | var architecture = DownloadArchitectureHelper.GetArchitecture(); 171 | var target = DownloadTargetHelper.GetTarget(options.Version); 172 | 173 | var mongoToolsVersions = await options.Transport.GetFromJsonAsync("https://downloads.mongodb.org/tools/db/release.json", cancellationToken).ConfigureAwait(false); 174 | 175 | var mongoToolsVersion = mongoToolsVersions.Versions.FirstOrDefault() 176 | ?? throw new EphemeralMongoException($"Could not find the latest MongoDB tools version"); 177 | 178 | var mongoToolsDownload = mongoToolsVersion.Downloads.SingleOrDefault(x => x.Architecture == architecture && x.Name == target) 179 | ?? throw new EphemeralMongoException($"Could not find the latest MongoDB tools version for architecture {architecture} and target {target}"); 180 | 181 | var exeDirPath = Path.Combine(baseExeDirPath, mongoToolsVersion.Version); 182 | var mongoImportExeFilePath = Path.Combine(exeDirPath, MongoImportExeFileName); 183 | var mongoExportExeFilePath = Path.Combine(exeDirPath, MongoExportExeFileName); 184 | 185 | if (File.Exists(mongoImportExeFilePath) && File.Exists(mongoExportExeFilePath)) 186 | { 187 | await UpdateLastCheckFileAsync(lastCheckFilePath).ConfigureAwait(false); 188 | return (mongoImportExeFilePath, mongoExportExeFilePath); 189 | } 190 | 191 | var tmpDirName = $"tools-{mongoToolsVersion.Version}-{Path.GetRandomFileName()}"; 192 | var tmpDownloadDirPath = Path.Combine(TmpDirPath, "downloads", tmpDirName); 193 | var tmpUncompressDirPath = Path.Combine(TmpDirPath, "uncompress", tmpDirName); 194 | 195 | Directory.CreateDirectory(exeDirPath); 196 | Directory.CreateDirectory(tmpDownloadDirPath); 197 | Directory.CreateDirectory(tmpUncompressDirPath); 198 | 199 | var tmpDownloadFilePath = Path.Combine(tmpDownloadDirPath, Path.GetFileName(mongoToolsDownload.Archive.Url)); 200 | 201 | try 202 | { 203 | await options.Transport.DownloadFileAsync(mongoToolsDownload.Archive.Url, tmpDownloadFilePath, cancellationToken).ConfigureAwait(false); 204 | await FileHashHelper.EnsureFileSha256HashAsync(tmpDownloadFilePath, mongoToolsDownload.Archive.Sha256, cancellationToken).ConfigureAwait(false); 205 | await FileCompressionHelper.ExtractToDirectoryAsync(tmpDownloadFilePath, tmpUncompressDirPath, cancellationToken).ConfigureAwait(false); 206 | 207 | var tmpUncompressedFirstDirPath = Directory.GetDirectories(tmpUncompressDirPath); 208 | if (tmpUncompressedFirstDirPath.Length != 1) 209 | { 210 | throw new EphemeralMongoException($"There should be only one directory in {tmpUncompressDirPath}, but found {tmpUncompressedFirstDirPath.Length}"); 211 | } 212 | 213 | var tmpMongoImportExeFilePath = Path.Combine(tmpUncompressedFirstDirPath[0], "bin", MongoImportExeFileName); 214 | var tmpMongoExportExeFilePath = Path.Combine(tmpUncompressedFirstDirPath[0], "bin", MongoExportExeFileName); 215 | 216 | if (!File.Exists(tmpMongoImportExeFilePath) || !File.Exists(tmpMongoExportExeFilePath)) 217 | { 218 | throw new EphemeralMongoException($"The executable files {tmpMongoImportExeFilePath} and {tmpMongoExportExeFilePath} could not be copied to {exeDirPath} because they do not exist"); 219 | } 220 | 221 | SafeFileCopy(tmpMongoImportExeFilePath, mongoImportExeFilePath); 222 | SafeFileCopy(tmpMongoExportExeFilePath, mongoExportExeFilePath); 223 | 224 | await UpdateLastCheckFileAsync(lastCheckFilePath).ConfigureAwait(false); 225 | return (mongoImportExeFilePath, mongoExportExeFilePath); 226 | } 227 | finally 228 | { 229 | DeleteQuietly(tmpDownloadDirPath); 230 | DeleteQuietly(tmpUncompressDirPath); 231 | } 232 | } 233 | finally 234 | { 235 | SharedMutex.Release(baseExeDirName); 236 | } 237 | } 238 | 239 | private static async Task UpdateLastCheckFileAsync(string lastCheckFilePath) 240 | { 241 | const int maxAttempts = 3; 242 | const int retryDelayMs = 50; 243 | 244 | for (var attempt = 1; attempt <= maxAttempts; attempt++) 245 | { 246 | try 247 | { 248 | // An IO conflict happened in Windows CI where the file was edited by another process (multi-assembly testing) 249 | #if NETSTANDARD2_0 250 | File.Create(lastCheckFilePath).Dispose(); 251 | #else 252 | await File.Create(lastCheckFilePath).DisposeAsync().ConfigureAwait(false); 253 | #endif 254 | return; 255 | } 256 | catch (IOException) 257 | { 258 | if (attempt == maxAttempts) 259 | { 260 | throw; 261 | } 262 | 263 | await Task.Delay(retryDelayMs).ConfigureAwait(false); 264 | } 265 | } 266 | } 267 | 268 | private static string? FindLatestExistingMongodExeFilePath(string baseExeDirPath) 269 | { 270 | var latestVersion = FindLatestDirectoryVersion(baseExeDirPath); 271 | if (latestVersion == null) 272 | { 273 | return null; 274 | } 275 | 276 | var exeDirPath = Path.Combine(baseExeDirPath, latestVersion.ToString()); 277 | var exeFilePath = Path.Combine(exeDirPath, MongodExeFileName); 278 | 279 | if (File.Exists(exeFilePath)) 280 | { 281 | return exeFilePath; 282 | } 283 | 284 | try 285 | { 286 | Directory.Delete(exeDirPath); 287 | } 288 | catch (IOException ex) 289 | { 290 | throw new EphemeralMongoException($"The directory {exeDirPath} did not contain the expected executable file {MongodExeFileName} and could not be deleted. Please delete it first.", ex); 291 | } 292 | 293 | return null; 294 | } 295 | 296 | private static (string MongoImportExePath, string MongoExportExePath)? FindLatestExistingToolExeFilePaths(string baseExeDirPath) 297 | { 298 | var latestVersion = FindLatestDirectoryVersion(baseExeDirPath); 299 | if (latestVersion == null) 300 | { 301 | return null; 302 | } 303 | 304 | var exeDirPath = Path.Combine(baseExeDirPath, latestVersion.ToString()); 305 | var mongoImportexeFilePath = Path.Combine(exeDirPath, MongoImportExeFileName); 306 | var mongoExportexeFilePath = Path.Combine(exeDirPath, MongoExportExeFileName); 307 | 308 | if (File.Exists(mongoImportexeFilePath) && File.Exists(mongoExportexeFilePath)) 309 | { 310 | return (mongoImportexeFilePath, mongoExportexeFilePath); 311 | } 312 | 313 | try 314 | { 315 | Directory.Delete(exeDirPath); 316 | } 317 | catch (IOException ex) 318 | { 319 | throw new EphemeralMongoException($"The directory {exeDirPath} did not contain the expected executable files {MongoImportExeFileName} and {MongoExportExeFileName} and could not be deleted. Please delete it first.", ex); 320 | } 321 | 322 | return null; 323 | } 324 | 325 | private static Version? FindLatestDirectoryVersion(string baseExeDirPath) 326 | { 327 | Version? latestVersion = null; 328 | foreach (var dirPath in Directory.EnumerateDirectories(baseExeDirPath, "*", SearchOption.TopDirectoryOnly)) 329 | { 330 | if (Version.TryParse(Path.GetFileName(dirPath), out var version) && (latestVersion == null || version > latestVersion)) 331 | { 332 | latestVersion = version; 333 | } 334 | } 335 | 336 | return latestVersion; 337 | } 338 | 339 | private static void DeleteQuietly(string path) 340 | { 341 | try 342 | { 343 | Directory.Delete(path, recursive: true); 344 | } 345 | catch (IOException) 346 | { 347 | // We did our best. OS can clean up later. 348 | } 349 | } 350 | 351 | private static void SafeFileCopy(string sourceFilePath, string destFilePath) 352 | { 353 | if (File.Exists(destFilePath)) 354 | { 355 | return; 356 | } 357 | 358 | try 359 | { 360 | File.Copy(sourceFilePath, destFilePath, overwrite: false); 361 | } 362 | catch (IOException) when (File.Exists(destFilePath)) 363 | { 364 | // Another process already copied the file, which is fine 365 | // This mostly happens in tests where we run two assemblies side by side (net9.0 and net472 for instance) 366 | } 367 | } 368 | } 369 | -------------------------------------------------------------------------------- /src/EphemeralMongo/Download/MongoVersionDto.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace EphemeralMongo.Download; 4 | 5 | internal sealed class MongoVersionDto 6 | { 7 | [JsonPropertyName("production_release")] 8 | public bool ProductionRelease { get; set; } 9 | 10 | [JsonPropertyName("version")] 11 | public string Version { get; set; } = string.Empty; 12 | 13 | [JsonPropertyName("downloads")] 14 | public MongoDownloadDto[] Downloads { get; set; } = []; 15 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/Download/MongoVersionsDto.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace EphemeralMongo.Download; 4 | 5 | internal sealed class MongoVersionsDto 6 | { 7 | [JsonPropertyName("versions")] 8 | public MongoVersionDto[] Versions { get; set; } = []; 9 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/Download/NamedMutex.cs: -------------------------------------------------------------------------------- 1 | namespace EphemeralMongo.Download; 2 | 3 | internal sealed class NamedMutex 4 | { 5 | private readonly Dictionary _mutexes; 6 | 7 | public NamedMutex() 8 | { 9 | this._mutexes = new Dictionary(StringComparer.Ordinal); 10 | } 11 | 12 | public Task WaitAsync(string name, CancellationToken cancellationToken) 13 | { 14 | return this.GetOrAdd(name).WaitAsync(cancellationToken); 15 | } 16 | 17 | private ReferenceAwareMutex GetOrAdd(string name) 18 | { 19 | lock (this._mutexes) 20 | { 21 | ReferenceAwareMutex mutex; 22 | 23 | if (this._mutexes.TryGetValue(name, out var existingMutex)) 24 | { 25 | mutex = existingMutex; 26 | } 27 | else 28 | { 29 | mutex = new ReferenceAwareMutex(); 30 | this._mutexes.Add(name, mutex); 31 | } 32 | 33 | mutex.IncrementReferenceCount(); 34 | return mutex; 35 | } 36 | } 37 | 38 | public void Release(string name) 39 | { 40 | lock (this._mutexes) 41 | { 42 | if (this._mutexes.TryGetValue(name, out var mutex)) 43 | { 44 | mutex.DecrementReferenceCount(); 45 | mutex.Release(); 46 | 47 | if (!mutex.IsReferenced) 48 | { 49 | this._mutexes.Remove(name); 50 | mutex.Dispose(); 51 | } 52 | } 53 | } 54 | } 55 | 56 | private sealed class ReferenceAwareMutex : IDisposable 57 | { 58 | private readonly SemaphoreSlim _mutex; 59 | 60 | // Accessing and modifying this field can be done without Interlocked because it's done inside a lock 61 | private int _referenceCount; 62 | 63 | public ReferenceAwareMutex() 64 | { 65 | this._mutex = new SemaphoreSlim(1, 1); 66 | this._referenceCount = 0; 67 | } 68 | 69 | public bool IsReferenced => this._referenceCount > 0; 70 | 71 | public async Task WaitAsync(CancellationToken cancellationToken) 72 | { 73 | await this._mutex.WaitAsync(cancellationToken).ConfigureAwait(false); 74 | } 75 | 76 | public void IncrementReferenceCount() => this._referenceCount++; 77 | 78 | public void DecrementReferenceCount() => this._referenceCount--; 79 | 80 | public void Release() 81 | { 82 | this._mutex.Release(); 83 | } 84 | 85 | public void Dispose() 86 | { 87 | this._mutex.Dispose(); 88 | } 89 | } 90 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/Download/RuntimeInformationHelper.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics.CodeAnalysis; 2 | using System.Runtime.InteropServices; 3 | 4 | namespace EphemeralMongo.Download; 5 | 6 | [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Same casing as System.Runtime.InteropServices.OSPlatform")] 7 | internal static class RuntimeInformationHelper 8 | { 9 | private static readonly Lazy LazyOSPlatform = new Lazy(GetOSPlatform); 10 | 11 | public static OSPlatform OSPlatform => LazyOSPlatform.Value; 12 | 13 | private static OSPlatform GetOSPlatform() 14 | { 15 | if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) 16 | { 17 | return OSPlatform.Windows; 18 | } 19 | 20 | if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) 21 | { 22 | return OSPlatform.OSX; 23 | } 24 | 25 | if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) 26 | { 27 | return OSPlatform.Linux; 28 | } 29 | 30 | throw new PlatformNotSupportedException($"Unsupported operating system {RuntimeInformation.OSDescription}"); 31 | } 32 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/Download/ToolsArchiveDto.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace EphemeralMongo.Download; 4 | 5 | internal sealed class ToolsArchiveDto 6 | { 7 | [JsonPropertyName("url")] 8 | public string Url { get; set; } = string.Empty; 9 | 10 | [JsonPropertyName("sha256")] 11 | public string Sha256 { get; set; } = string.Empty; 12 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/Download/ToolsDownloadDto.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace EphemeralMongo.Download; 4 | 5 | internal sealed class ToolsDownloadDto 6 | { 7 | [JsonPropertyName("name")] 8 | public string Name { get; set; } = string.Empty; 9 | 10 | [JsonPropertyName("arch")] 11 | public string Architecture { get; set; } = string.Empty; 12 | 13 | [JsonPropertyName("archive")] 14 | public ToolsArchiveDto Archive { get; set; } = new ToolsArchiveDto(); 15 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/Download/ToolsVersionDto.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace EphemeralMongo.Download; 4 | 5 | internal sealed class ToolsVersionDto 6 | { 7 | [JsonPropertyName("version")] 8 | public string Version { get; set; } = string.Empty; 9 | 10 | [JsonPropertyName("downloads")] 11 | public ToolsDownloadDto[] Downloads { get; set; } = []; 12 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/Download/ToolsVersionsDto.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace EphemeralMongo.Download; 4 | 5 | internal sealed class ToolsVersionsDto 6 | { 7 | [JsonPropertyName("versions")] 8 | public ToolsVersionDto[] Versions { get; set; } = []; 9 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/EphemeralMongo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | netstandard2.1;net8.0 4 | EphemeralMongo 5 | EphemeralMongo 6 | EphemeralMongo 7 | true 8 | Provides access to preconfigured MongoDB servers for testing purposes, without Docker or other dependencies. 9 | README.md 10 | true 11 | $(DefineConstants);MONGODB_V3 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | all 24 | runtime; build; native; contentfiles; analyzers 25 | 26 | 27 | all 28 | runtime; build; native; contentfiles; analyzers 29 | 30 | 31 | all 32 | runtime; build; native; contentfiles; analyzers 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /src/EphemeralMongo/EphemeralMongoException.cs: -------------------------------------------------------------------------------- 1 | namespace EphemeralMongo; 2 | 3 | public sealed class EphemeralMongoException : Exception 4 | { 5 | public EphemeralMongoException(string message) 6 | : base(message) 7 | { 8 | } 9 | 10 | public EphemeralMongoException(string message, Exception innerException) 11 | : base(message, innerException) 12 | { 13 | } 14 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/ExperimentalAttribute.cs: -------------------------------------------------------------------------------- 1 | // Licensed to the .NET Foundation under one or more agreements. 2 | // The .NET Foundation licenses this file to you under the MIT license. 3 | 4 | // This was adapted from https://github.com/dotnet/runtime/blob/v9.0.4/src/libraries/System.Private.CoreLib/src/System/Diagnostics/CodeAnalysis/ExperimentalAttribute.cs 5 | 6 | #pragma warning disable 7 | 8 | #if !NET8_0_OR_GREATER 9 | 10 | namespace System.Diagnostics.CodeAnalysis 11 | { 12 | [AttributeUsage(AttributeTargets.Assembly | 13 | AttributeTargets.Module | 14 | AttributeTargets.Class | 15 | AttributeTargets.Struct | 16 | AttributeTargets.Enum | 17 | AttributeTargets.Constructor | 18 | AttributeTargets.Method | 19 | AttributeTargets.Property | 20 | AttributeTargets.Field | 21 | AttributeTargets.Event | 22 | AttributeTargets.Interface | 23 | AttributeTargets.Delegate, Inherited = false)] 24 | internal sealed class ExperimentalAttribute : Attribute 25 | { 26 | public ExperimentalAttribute(string diagnosticId) 27 | { 28 | // ReSharper disable once ArrangeThisQualifier 29 | DiagnosticId = diagnosticId; 30 | } 31 | 32 | public string DiagnosticId { get; } 33 | 34 | public string? UrlFormat { get; set; } 35 | } 36 | } 37 | 38 | #endif // !NET8_0_OR_LATER -------------------------------------------------------------------------------- /src/EphemeralMongo/FileSystem.cs: -------------------------------------------------------------------------------- 1 | #if !NET8_0_OR_GREATER 2 | using System.Diagnostics; 3 | #endif 4 | using System.Runtime.InteropServices; 5 | 6 | namespace EphemeralMongo; 7 | 8 | internal sealed class FileSystem : IFileSystem 9 | { 10 | public void CreateDirectory(string path) 11 | { 12 | Directory.CreateDirectory(path); 13 | } 14 | 15 | public void DeleteDirectory(string path) 16 | { 17 | Directory.Delete(path, recursive: true); 18 | } 19 | 20 | public void DeleteFile(string path) 21 | { 22 | File.Delete(path); 23 | } 24 | 25 | public string[] GetDirectories(string path, string searchPattern, SearchOption searchOption) 26 | { 27 | return Directory.GetDirectories(path, searchPattern, searchOption); 28 | } 29 | 30 | public DateTime GetDirectoryCreationTimeUtc(string path) 31 | { 32 | return Directory.GetCreationTimeUtc(path); 33 | } 34 | 35 | public void MakeFileExecutable(string path) 36 | { 37 | if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && !RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) 38 | { 39 | return; 40 | } 41 | 42 | try 43 | { 44 | #if NET8_0_OR_GREATER 45 | const UnixFileMode executePermissions = UnixFileMode.UserExecute | UnixFileMode.GroupExecute | UnixFileMode.OtherExecute; 46 | 47 | var unixFileMode = File.GetUnixFileMode(path); 48 | var alreadyExecutable = (unixFileMode & executePermissions) != UnixFileMode.None; 49 | 50 | if (!alreadyExecutable) 51 | { 52 | File.SetUnixFileMode(path, unixFileMode | executePermissions); 53 | } 54 | #else 55 | using var test = Process.Start("test", "-x " + ProcessArgument.Escape(path)); 56 | test?.WaitForExit(); 57 | 58 | var alreadyExecutable = test?.ExitCode == 0; 59 | if (alreadyExecutable) 60 | { 61 | return; 62 | } 63 | 64 | using var chmod = Process.Start("chmod", "+x " + ProcessArgument.Escape(path)); 65 | chmod?.WaitForExit(); 66 | #endif 67 | } 68 | catch 69 | { 70 | // Do not throw if something wrong happens 71 | // If there's something wrong with the path or permissions, we'll see it later. 72 | } 73 | } 74 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/HttpTransport.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics.CodeAnalysis; 2 | using System.Text.Json; 3 | 4 | namespace EphemeralMongo; 5 | 6 | [SuppressMessage("Design", "CA1001:Types that own disposable fields should be disposable", Justification = "HttpClient is a singleton or managed by the caller")] 7 | public sealed class HttpTransport 8 | { 9 | #if NET8_0_OR_GREATER 10 | private static readonly HttpClient SharedDefaultHttpClient = new HttpClient(new SocketsHttpHandler 11 | { 12 | PooledConnectionLifetime = TimeSpan.FromMinutes(5) 13 | }); 14 | #else 15 | private static readonly HttpClient SharedDefaultHttpClient = new HttpClient(); 16 | #endif 17 | 18 | private readonly HttpClient _httpClient; 19 | 20 | public HttpTransport(HttpClient httpClient) 21 | { 22 | this._httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); 23 | } 24 | 25 | internal HttpTransport() 26 | : this(SharedDefaultHttpClient) 27 | { 28 | } 29 | 30 | public HttpTransport(HttpMessageHandler handler) 31 | { 32 | if (handler == null) 33 | { 34 | throw new ArgumentNullException(nameof(handler)); 35 | } 36 | 37 | this._httpClient = new HttpClient(handler); 38 | } 39 | 40 | internal async Task DownloadFileAsync(string url, string filePath, CancellationToken cancellationToken) 41 | { 42 | try 43 | { 44 | using var response = await this._httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); 45 | response.EnsureSuccessStatusCode(); 46 | 47 | #if NET8_0_OR_GREATER 48 | Stream sourceStream; 49 | Stream destinationStream; 50 | await using ((sourceStream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false)).ConfigureAwait(false)) 51 | await using ((destinationStream = File.Create(filePath)).ConfigureAwait(false)) 52 | { 53 | await sourceStream.CopyToAsync(destinationStream, cancellationToken).ConfigureAwait(false); 54 | } 55 | #else 56 | using var sourceStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); 57 | using var destinationStream = File.Create(filePath); 58 | 59 | const int defaultBufferSize = 81920; 60 | await sourceStream.CopyToAsync(destinationStream, defaultBufferSize, cancellationToken).ConfigureAwait(false); 61 | #endif 62 | } 63 | catch (Exception ex) 64 | { 65 | throw new EphemeralMongoException($"An error occurred while downloading the file from {url} to {filePath}", ex); 66 | } 67 | } 68 | 69 | internal async Task GetFromJsonAsync(string url, CancellationToken cancellationToken) 70 | { 71 | TValue? value; 72 | try 73 | { 74 | using var response = await this._httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); 75 | response.EnsureSuccessStatusCode(); 76 | 77 | Stream stream; 78 | #if NET8_0_OR_GREATER 79 | await using ((stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false)).ConfigureAwait(false)) 80 | #elif NETSTANDARD2_1_OR_GREATER 81 | await using ((stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)).ConfigureAwait(false)) 82 | #else 83 | using (stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) 84 | #endif 85 | { 86 | value = await JsonSerializer.DeserializeAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false); 87 | } 88 | } 89 | catch (Exception ex) 90 | { 91 | throw new EphemeralMongoException($"An error occurred while parsing {url} as a JSON response", ex); 92 | } 93 | 94 | return value ?? throw new EphemeralMongoException($"An error occurred while parsing {url} as a JSON response"); 95 | } 96 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/IFileSystem.cs: -------------------------------------------------------------------------------- 1 | namespace EphemeralMongo; 2 | 3 | internal interface IFileSystem 4 | { 5 | void CreateDirectory(string path); 6 | 7 | void DeleteDirectory(string path); 8 | 9 | void DeleteFile(string path); 10 | 11 | string[] GetDirectories(string path, string searchPattern, SearchOption searchOption); 12 | 13 | DateTime GetDirectoryCreationTimeUtc(string path); 14 | 15 | void MakeFileExecutable(string path); 16 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/IMongoExecutableLocator.cs: -------------------------------------------------------------------------------- 1 | namespace EphemeralMongo; 2 | 3 | internal interface IMongoExecutableLocator 4 | { 5 | Task FindMongoExecutablePathAsync(MongoRunnerOptions options, MongoProcessKind processKind, CancellationToken cancellationToken); 6 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/IMongoProcess.cs: -------------------------------------------------------------------------------- 1 | namespace EphemeralMongo; 2 | 3 | internal interface IMongoProcess : IDisposable 4 | { 5 | Task StartAsync(CancellationToken cancellationToken); 6 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/IMongoProcessFactory.cs: -------------------------------------------------------------------------------- 1 | namespace EphemeralMongo; 2 | 3 | internal interface IMongoProcessFactory 4 | { 5 | IMongoProcess CreateMongoProcess(MongoRunnerOptions options, MongoProcessKind processKind, string executablePath, string[] arguments); 6 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/IMongoRunner.cs: -------------------------------------------------------------------------------- 1 | namespace EphemeralMongo; 2 | 3 | public interface IMongoRunner : IDisposable 4 | { 5 | string ConnectionString { get; } 6 | 7 | Task ImportAsync(string database, string collection, string inputFilePath, string[]? additionalArguments = null, bool drop = false, CancellationToken cancellationToken = default); 8 | 9 | void Import(string database, string collection, string inputFilePath, string[]? additionalArguments = null, bool drop = false, CancellationToken cancellationToken = default); 10 | 11 | Task ExportAsync(string database, string collection, string outputFilePath, string[]? additionalArguments = null, CancellationToken cancellationToken = default); 12 | 13 | void Export(string database, string collection, string outputFilePath, string[]? additionalArguments = null, CancellationToken cancellationToken = default); 14 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/IPortFactory.cs: -------------------------------------------------------------------------------- 1 | namespace EphemeralMongo; 2 | 3 | internal interface IPortFactory 4 | { 5 | int GetRandomAvailablePort(); 6 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/ITimeProvider.cs: -------------------------------------------------------------------------------- 1 | namespace EphemeralMongo; 2 | 3 | internal interface ITimeProvider 4 | { 5 | DateTimeOffset UtcNow { get; } 6 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/Logger.cs: -------------------------------------------------------------------------------- 1 | namespace EphemeralMongo; 2 | 3 | public delegate void Logger(string text); -------------------------------------------------------------------------------- /src/EphemeralMongo/MongoEdition.cs: -------------------------------------------------------------------------------- 1 | namespace EphemeralMongo; 2 | 3 | public enum MongoEdition 4 | { 5 | Community, 6 | Enterprise, 7 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/MongoExecutableLocator.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.InteropServices; 2 | using EphemeralMongo.Download; 3 | 4 | namespace EphemeralMongo; 5 | 6 | internal sealed class MongoExecutableLocator : IMongoExecutableLocator 7 | { 8 | private static readonly Dictionary MongodExecutableFileNameMappings = new Dictionary 9 | { 10 | [OSPlatform.Windows] = "mongod.exe", 11 | [OSPlatform.Linux] = "mongod", 12 | [OSPlatform.OSX] = "mongod", 13 | }; 14 | 15 | private static readonly Dictionary MongoImportExecutableFileNameMappings = new Dictionary 16 | { 17 | [OSPlatform.Windows] = "mongoimport.exe", 18 | [OSPlatform.Linux] = "mongoimport", 19 | [OSPlatform.OSX] = "mongoimport", 20 | }; 21 | 22 | private static readonly Dictionary MongoExportExecutableFileNameMappings = new Dictionary 23 | { 24 | [OSPlatform.Windows] = "mongoexport.exe", 25 | [OSPlatform.Linux] = "mongoexport", 26 | [OSPlatform.OSX] = "mongoexport", 27 | }; 28 | 29 | private static readonly Dictionary AnyMongoExecutableFileNameMappings = new Dictionary 30 | { 31 | [MongoProcessKind.Mongod] = GetMongoExecutableFileName(MongodExecutableFileNameMappings), 32 | [MongoProcessKind.MongoImport] = GetMongoExecutableFileName(MongoImportExecutableFileNameMappings), 33 | [MongoProcessKind.MongoExport] = GetMongoExecutableFileName(MongoExportExecutableFileNameMappings), 34 | }; 35 | 36 | private static string GetMongoExecutableFileName(Dictionary mappings) => 37 | mappings.Where(x => RuntimeInformation.IsOSPlatform(x.Key)).Select(x => x.Value).FirstOrDefault() 38 | ?? throw new NotSupportedException("Current operating system is not supported"); 39 | 40 | public async Task FindMongoExecutablePathAsync(MongoRunnerOptions options, MongoProcessKind processKind, CancellationToken cancellationToken) 41 | { 42 | var executableFileName = AnyMongoExecutableFileNameMappings[processKind]; 43 | 44 | if (options.BinaryDirectory != null) 45 | { 46 | var userProvidedExecutableFilePath = Path.Combine(options.BinaryDirectory, executableFileName); 47 | if (!File.Exists(userProvidedExecutableFilePath)) 48 | { 49 | throw new FileNotFoundException($"The provided binary directory '{options.BinaryDirectory}' does not contain the executable '{executableFileName}'.", userProvidedExecutableFilePath); 50 | } 51 | } 52 | 53 | if (processKind == MongoProcessKind.Mongod) 54 | { 55 | return await MongoExecutableDownloader.DownloadMongodAsync(options, cancellationToken).ConfigureAwait(false); 56 | } 57 | 58 | var paths = await MongoExecutableDownloader.DownloadMongoToolsAsync(options, cancellationToken).ConfigureAwait(false); 59 | 60 | return processKind == MongoProcessKind.MongoImport ? paths.MongoImportExePath : paths.MongoExportExePath; 61 | } 62 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/MongoImportExportProcess.cs: -------------------------------------------------------------------------------- 1 | namespace EphemeralMongo; 2 | 3 | internal sealed class MongoImportExportProcess : BaseMongoProcess 4 | { 5 | public MongoImportExportProcess(MongoRunnerOptions options, string executablePath, string[] arguments) 6 | : base(options, executablePath, arguments) 7 | { 8 | } 9 | 10 | #if NET8_0_OR_GREATER 11 | public override async Task StartAsync(CancellationToken cancellationToken) 12 | #else 13 | public override Task StartAsync(CancellationToken cancellationToken) 14 | #endif 15 | { 16 | this.Process.Start(); 17 | 18 | this.Process.BeginOutputReadLine(); 19 | this.Process.BeginErrorReadLine(); 20 | 21 | // Wait for the end of import or export 22 | #if NET8_0_OR_GREATER 23 | await this.Process.WaitForExitAsync(cancellationToken).ConfigureAwait(false); 24 | #else 25 | this.Process.WaitForExit(); 26 | return Task.CompletedTask; 27 | #endif 28 | } 29 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/MongoProcessFactory.cs: -------------------------------------------------------------------------------- 1 | namespace EphemeralMongo; 2 | 3 | internal sealed class MongoProcessFactory : IMongoProcessFactory 4 | { 5 | public IMongoProcess CreateMongoProcess(MongoRunnerOptions options, MongoProcessKind processKind, string executablePath, string[] arguments) 6 | { 7 | var escapedArguments = new string[arguments.Length]; 8 | 9 | for (var i = 0; i < arguments.Length; i++) 10 | { 11 | escapedArguments[i] = ProcessArgument.Escape(arguments[i]); 12 | } 13 | 14 | return processKind == MongoProcessKind.Mongod 15 | ? new MongodProcess(options, executablePath, escapedArguments) 16 | : new MongoImportExportProcess(options, executablePath, escapedArguments); 17 | } 18 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/MongoProcessKind.cs: -------------------------------------------------------------------------------- 1 | namespace EphemeralMongo; 2 | 3 | internal enum MongoProcessKind 4 | { 5 | Mongod, 6 | MongoImport, 7 | MongoExport, 8 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/MongoRunner.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics.CodeAnalysis; 2 | using System.Globalization; 3 | using System.Runtime.ExceptionServices; 4 | using System.Runtime.InteropServices; 5 | using MongoDB.Bson; 6 | using MongoDB.Driver; 7 | 8 | namespace EphemeralMongo; 9 | 10 | public sealed class MongoRunner 11 | { 12 | private static readonly string DefaultRootDataDirectory = Path.Combine(Path.GetTempPath(), "ephemeral-mongo", "data"); 13 | 14 | private readonly IFileSystem _fileSystem; 15 | private readonly ITimeProvider _timeProvider; 16 | private readonly IPortFactory _portFactory; 17 | private readonly IMongoExecutableLocator _executableLocator; 18 | private readonly IMongoProcessFactory _processFactory; 19 | private readonly MongoRunnerOptions _options; 20 | 21 | private IMongoProcess? _process; 22 | private string? _dataDirectory; 23 | 24 | private MongoRunner(IFileSystem fileSystem, ITimeProvider timeProvider, IPortFactory portFactory, IMongoExecutableLocator executableLocator, IMongoProcessFactory processFactory, MongoRunnerOptions? options = null) 25 | { 26 | this._fileSystem = fileSystem; 27 | this._timeProvider = timeProvider; 28 | this._portFactory = portFactory; 29 | this._executableLocator = executableLocator; 30 | this._processFactory = processFactory; 31 | this._options = options == null ? new MongoRunnerOptions() : new MongoRunnerOptions(options); 32 | } 33 | 34 | public static Task RunAsync(MongoRunnerOptions? options = null, CancellationToken cancellationToken = default) 35 | { 36 | var runner = new MongoRunner(new FileSystem(), new TimeProvider(), new PortFactory(), new MongoExecutableLocator(), new MongoProcessFactory(), options); 37 | return runner.RunInternalAsync(cancellationToken); 38 | } 39 | 40 | public static IMongoRunner Run(MongoRunnerOptions? options = null, CancellationToken cancellationToken = default) 41 | { 42 | return RunAsync(options, cancellationToken).ConfigureAwait(false).GetAwaiter().GetResult(); 43 | } 44 | 45 | private async Task RunInternalAsync(CancellationToken cancellationToken) 46 | { 47 | try 48 | { 49 | // Find MongoDB and make it executable 50 | var executablePath = await this._executableLocator.FindMongoExecutablePathAsync(this._options, MongoProcessKind.Mongod, cancellationToken).ConfigureAwait(false); 51 | this._fileSystem.MakeFileExecutable(executablePath); 52 | 53 | // Ensure data directory exists... 54 | if (this._options.DataDirectory != null) 55 | { 56 | this._dataDirectory = this._options.DataDirectory; 57 | } 58 | else 59 | { 60 | this._options.RootDataDirectoryPath ??= DefaultRootDataDirectory; 61 | this._dataDirectory = Path.Combine(this._options.RootDataDirectoryPath, Path.GetRandomFileName()); 62 | } 63 | 64 | this._fileSystem.CreateDirectory(this._dataDirectory); 65 | 66 | try 67 | { 68 | // ...and has no existing MongoDB lock file 69 | // https://stackoverflow.com/a/6857973/825695 70 | var lockFilePath = Path.Combine(this._dataDirectory, "mongod.lock"); 71 | this._fileSystem.DeleteFile(lockFilePath); 72 | } 73 | catch 74 | { 75 | // Ignored - this data directory might already be in use, we'll see later how mongod reacts 76 | } 77 | 78 | this.CleanupOldDataDirectories(); 79 | 80 | this._options.MongoPort ??= this._portFactory.GetRandomAvailablePort(); 81 | 82 | // Build mongod executable arguments 83 | List arguments = 84 | [ 85 | "--dbpath", this._dataDirectory, 86 | "--port", this._options.MongoPort.Value.ToString(CultureInfo.InvariantCulture), 87 | "--bind_ip", "127.0.0.1" 88 | ]; 89 | 90 | if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) 91 | { 92 | arguments.Add("--tlsMode"); 93 | arguments.Add("disabled"); 94 | } 95 | 96 | if (this._options.UseSingleNodeReplicaSet) 97 | { 98 | arguments.Add("--replSet"); 99 | arguments.Add(this._options.ReplicaSetName); 100 | } 101 | 102 | if (this._options.AdditionalArguments != null) 103 | { 104 | foreach (var additionalArgument in this._options.AdditionalArguments) 105 | { 106 | if (!string.IsNullOrWhiteSpace(additionalArgument)) 107 | { 108 | arguments.Add(additionalArgument); 109 | } 110 | } 111 | } 112 | 113 | this._process = this._processFactory.CreateMongoProcess(this._options, MongoProcessKind.Mongod, executablePath, [.. arguments]); 114 | await this._process.StartAsync(cancellationToken).ConfigureAwait(false); 115 | 116 | var connectionStringFormat = this._options.UseSingleNodeReplicaSet ? "mongodb://127.0.0.1:{0}/?directConnection=true&replicaSet={1}&readPreference=primary" : "mongodb://127.0.0.1:{0}"; 117 | var connectionString = string.Format(CultureInfo.InvariantCulture, connectionStringFormat, this._options.MongoPort, this._options.ReplicaSetName); 118 | 119 | return new StartedMongoRunner(this, connectionString); 120 | } 121 | catch 122 | { 123 | this.Dispose(throwOnException: false); 124 | throw; 125 | } 126 | } 127 | 128 | private static int _ongoingRootDataDirectoryCleanupCount; 129 | 130 | private void CleanupOldDataDirectories() 131 | { 132 | if (this._options.DataDirectory != null) 133 | { 134 | // Data directory was set by user, do not trigger cleanup 135 | return; 136 | } 137 | 138 | try 139 | { 140 | var isCleanupOngoing = Interlocked.Increment(ref _ongoingRootDataDirectoryCleanupCount) > 1; 141 | if (isCleanupOngoing) 142 | { 143 | return; 144 | } 145 | 146 | string[] dataDirectoryPaths; 147 | try 148 | { 149 | dataDirectoryPaths = this._fileSystem.GetDirectories(this._options.RootDataDirectoryPath!, "*", SearchOption.TopDirectoryOnly); 150 | } 151 | catch (Exception ex) 152 | { 153 | this._options.StandardErrorLogger?.Invoke($"An error occurred while trying to enumerate existing data directories for cleanup in '{DefaultRootDataDirectory}': {ex.Message}"); 154 | return; 155 | } 156 | 157 | foreach (var dataDirectoryPath in dataDirectoryPaths) 158 | { 159 | try 160 | { 161 | var dataDirectoryAge = this._timeProvider.UtcNow - this._fileSystem.GetDirectoryCreationTimeUtc(dataDirectoryPath); 162 | if (dataDirectoryAge >= this._options.DataDirectoryLifetime) 163 | { 164 | this._fileSystem.DeleteDirectory(dataDirectoryPath); 165 | } 166 | } 167 | catch (Exception ex) 168 | { 169 | this._options.StandardErrorLogger?.Invoke($"An error occurred while trying to delete old data directory '{dataDirectoryPath}': {ex.Message}"); 170 | } 171 | } 172 | } 173 | finally 174 | { 175 | Interlocked.Decrement(ref _ongoingRootDataDirectoryCleanupCount); 176 | } 177 | } 178 | 179 | private void Dispose(bool throwOnException) 180 | { 181 | var exceptions = new List(1); 182 | 183 | try 184 | { 185 | this._process?.Dispose(); 186 | } 187 | catch (Exception ex) 188 | { 189 | exceptions.Add(ex); 190 | } 191 | 192 | try 193 | { 194 | // Do not dispose data directory if set from user input or the root data directory path was set for tests 195 | if (this._dataDirectory != null && this._options.DataDirectory == null && this._options.RootDataDirectoryPath == DefaultRootDataDirectory) 196 | { 197 | this._fileSystem.DeleteDirectory(this._dataDirectory); 198 | } 199 | } 200 | catch (Exception ex) 201 | { 202 | exceptions.Add(ex); 203 | } 204 | 205 | if (throwOnException) 206 | { 207 | if (exceptions.Count == 1) 208 | { 209 | ExceptionDispatchInfo.Capture(exceptions[0]).Throw(); 210 | } 211 | else if (exceptions.Count > 1) 212 | { 213 | throw new AggregateException(exceptions); 214 | } 215 | } 216 | } 217 | 218 | private sealed class StartedMongoRunner : IMongoRunner 219 | { 220 | private readonly MongoRunner _runner; 221 | private int _isDisposed; 222 | 223 | public StartedMongoRunner(MongoRunner runner, string connectionString) 224 | { 225 | this._runner = runner; 226 | this.ConnectionString = connectionString; 227 | } 228 | 229 | public string ConnectionString { get; } 230 | 231 | [SuppressMessage("Maintainability", "CA1513", Justification = "ObjectDisposedException.ThrowIf isn't worth it when multi-targeting")] 232 | public async Task ImportAsync(string database, string collection, string inputFilePath, string[]? additionalArguments = null, bool drop = false, CancellationToken cancellationToken = default) 233 | { 234 | if (Interlocked.CompareExchange(ref this._isDisposed, 0, 0) == 1) 235 | { 236 | throw new ObjectDisposedException("MongoDB runner is already disposed"); 237 | } 238 | 239 | if (string.IsNullOrWhiteSpace(database)) 240 | { 241 | throw new ArgumentException("Database name is required", nameof(database)); 242 | } 243 | 244 | if (string.IsNullOrWhiteSpace(collection)) 245 | { 246 | throw new ArgumentException("Collection name is required", nameof(collection)); 247 | } 248 | 249 | if (string.IsNullOrWhiteSpace(inputFilePath)) 250 | { 251 | throw new ArgumentException("Input file path is required", nameof(inputFilePath)); 252 | } 253 | 254 | var executablePath = await this._runner._executableLocator.FindMongoExecutablePathAsync(this._runner._options, MongoProcessKind.MongoImport, cancellationToken).ConfigureAwait(false); 255 | this._runner._fileSystem.MakeFileExecutable(executablePath); 256 | 257 | List arguments = 258 | [ 259 | "--uri", this.ConnectionString, 260 | "--db", database, 261 | "--collection", collection, 262 | "--file", inputFilePath 263 | ]; 264 | 265 | if (drop) 266 | { 267 | arguments.Add("--drop"); 268 | } 269 | 270 | if (additionalArguments != null) 271 | { 272 | foreach (var additionalArgument in additionalArguments) 273 | { 274 | if (!string.IsNullOrWhiteSpace(additionalArgument)) 275 | { 276 | arguments.Add(additionalArgument); 277 | } 278 | } 279 | } 280 | 281 | using (var process = this._runner._processFactory.CreateMongoProcess(this._runner._options, MongoProcessKind.MongoImport, executablePath, [.. arguments])) 282 | { 283 | await process.StartAsync(cancellationToken).ConfigureAwait(false); 284 | } 285 | } 286 | 287 | public void Import(string database, string collection, string inputFilePath, string[]? additionalArguments = null, bool drop = false, CancellationToken cancellationToken = default) 288 | { 289 | this.ImportAsync(database, collection, inputFilePath, additionalArguments, drop, cancellationToken).ConfigureAwait(false).GetAwaiter().GetResult(); 290 | } 291 | 292 | [SuppressMessage("Maintainability", "CA1513", Justification = "ObjectDisposedException.ThrowIf isn't worth it when multi-targeting")] 293 | public async Task ExportAsync(string database, string collection, string outputFilePath, string[]? additionalArguments = null, CancellationToken cancellationToken = default) 294 | { 295 | if (Interlocked.CompareExchange(ref this._isDisposed, 0, 0) == 1) 296 | { 297 | throw new ObjectDisposedException("MongoDB runner is already disposed"); 298 | } 299 | 300 | if (string.IsNullOrWhiteSpace(database)) 301 | { 302 | throw new ArgumentException("Database name is required", nameof(database)); 303 | } 304 | 305 | if (string.IsNullOrWhiteSpace(collection)) 306 | { 307 | throw new ArgumentException("Collection name is required", nameof(collection)); 308 | } 309 | 310 | if (string.IsNullOrWhiteSpace(outputFilePath)) 311 | { 312 | throw new ArgumentException("Output file path is required", nameof(outputFilePath)); 313 | } 314 | 315 | var executablePath = await this._runner._executableLocator.FindMongoExecutablePathAsync(this._runner._options, MongoProcessKind.MongoExport, cancellationToken).ConfigureAwait(false); 316 | this._runner._fileSystem.MakeFileExecutable(executablePath); 317 | 318 | var arguments = new List 319 | { 320 | "--uri", this.ConnectionString, 321 | "--db", database, 322 | "--collection", collection, 323 | "--out", outputFilePath 324 | }; 325 | 326 | if (additionalArguments != null) 327 | { 328 | foreach (var additionalArgument in additionalArguments) 329 | { 330 | if (!string.IsNullOrWhiteSpace(additionalArgument)) 331 | { 332 | arguments.Add(additionalArgument); 333 | } 334 | } 335 | } 336 | 337 | using (var process = this._runner._processFactory.CreateMongoProcess(this._runner._options, MongoProcessKind.MongoExport, executablePath, [.. arguments])) 338 | { 339 | await process.StartAsync(cancellationToken).ConfigureAwait(false); 340 | } 341 | } 342 | 343 | public void Export(string database, string collection, string outputFilePath, string[]? additionalArguments = null, CancellationToken cancellationToken = default) 344 | { 345 | this.ExportAsync(database, collection, outputFilePath, additionalArguments, cancellationToken).ConfigureAwait(false).GetAwaiter().GetResult(); 346 | } 347 | 348 | public void Dispose() 349 | { 350 | if (Interlocked.CompareExchange(ref this._isDisposed, 1, 0) == 0) 351 | { 352 | this.TryShutdownQuietly(); 353 | this._runner.Dispose(throwOnException: true); 354 | } 355 | } 356 | 357 | private void TryShutdownQuietly() 358 | { 359 | // https://www.mongodb.com/docs/v4.4/reference/command/shutdown/ 360 | const int defaultShutdownTimeoutInSeconds = 10; 361 | 362 | var shutdownCommand = new BsonDocument 363 | { 364 | { "shutdown", 1 }, 365 | { "force", true }, 366 | { "timeoutSecs", defaultShutdownTimeoutInSeconds }, 367 | }; 368 | 369 | try 370 | { 371 | var client = new MongoClient(this.ConnectionString); 372 | var admin = client.GetDatabase("admin"); 373 | 374 | using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(defaultShutdownTimeoutInSeconds))) 375 | { 376 | admin.RunCommand(shutdownCommand, cancellationToken: cts.Token); 377 | } 378 | } 379 | catch (MongoConnectionException) 380 | { 381 | // This is the expected behavior as mongod is shutting down 382 | } 383 | catch 384 | { 385 | // Ignore other exceptions as well, we'll kill the process anyway 386 | } 387 | } 388 | } 389 | } 390 | -------------------------------------------------------------------------------- /src/EphemeralMongo/MongoRunnerOptions.cs: -------------------------------------------------------------------------------- 1 | namespace EphemeralMongo; 2 | 3 | public sealed class MongoRunnerOptions 4 | { 5 | private MongoVersion _version = MongoVersion.V8; 6 | private MongoEdition _edition = MongoEdition.Community; 7 | private string? _dataDirectory; 8 | private string? _binaryDirectory; 9 | private TimeSpan _connectionTimeout = TimeSpan.FromSeconds(30); 10 | private TimeSpan _replicaSetSetupTimeout = TimeSpan.FromSeconds(10); 11 | private int? _mongoPort; 12 | private TimeSpan _dataDirectoryLifetime = TimeSpan.FromHours(12); 13 | private HttpTransport _httpTransport = new HttpTransport(); 14 | private TimeSpan _newVersionCheckTimeout = TimeSpan.FromDays(1); 15 | 16 | public MongoRunnerOptions() 17 | { 18 | } 19 | 20 | internal MongoRunnerOptions(MongoRunnerOptions options) 21 | { 22 | if (options == null) 23 | { 24 | throw new ArgumentNullException(nameof(options)); 25 | } 26 | 27 | this._version = options._version; 28 | this._edition = options._edition; 29 | this._dataDirectory = options._dataDirectory; 30 | this._binaryDirectory = options._binaryDirectory; 31 | this._connectionTimeout = options._connectionTimeout; 32 | this._replicaSetSetupTimeout = options._replicaSetSetupTimeout; 33 | this._mongoPort = options._mongoPort; 34 | this._dataDirectoryLifetime = options._dataDirectoryLifetime; 35 | this._httpTransport = options._httpTransport; 36 | this._newVersionCheckTimeout = options._newVersionCheckTimeout; 37 | 38 | this.AdditionalArguments = options.AdditionalArguments; 39 | this.UseSingleNodeReplicaSet = options.UseSingleNodeReplicaSet; 40 | this.StandardOutputLogger = options.StandardOutputLogger; 41 | this.StandardErrorLogger = options.StandardErrorLogger; 42 | this.ReplicaSetName = options.ReplicaSetName; 43 | this.RootDataDirectoryPath = options.RootDataDirectoryPath; 44 | } 45 | 46 | /// 47 | /// The desired MongoDB version to download and use. 48 | /// 49 | /// The version is not supported. 50 | public MongoVersion Version 51 | { 52 | get => this._version; 53 | set => this._version = Enum.IsDefined(typeof(MongoVersion), value) ? value : throw new ArgumentOutOfRangeException(nameof(this.Version)); 54 | } 55 | 56 | /// 57 | /// The desired MongoDB edition to download and use. 58 | /// 59 | /// The edition is not supported. 60 | public MongoEdition Edition 61 | { 62 | get => this._edition; 63 | set => this._edition = Enum.IsDefined(typeof(MongoEdition), value) ? value : throw new ArgumentOutOfRangeException(nameof(this.Edition)); 64 | } 65 | 66 | /// 67 | /// The directory where the mongod instance stores its data. If not specified, a temporary directory will be used. 68 | /// 69 | /// The path is invalid. 70 | /// 71 | public string? DataDirectory 72 | { 73 | get => this._dataDirectory; 74 | set => this._dataDirectory = CheckDirectoryPathFormat(value) is { } ex ? throw new ArgumentException(nameof(this.DataDirectory), ex) : value; 75 | } 76 | 77 | /// 78 | /// The directory where your own MongoDB binaries can be found (mongod, mongoexport and mongoimport). 79 | /// 80 | /// The path is invalid. 81 | public string? BinaryDirectory 82 | { 83 | get => this._binaryDirectory; 84 | set => this._binaryDirectory = CheckDirectoryPathFormat(value) is { } ex ? throw new ArgumentException(nameof(this.BinaryDirectory), ex) : value; 85 | } 86 | 87 | /// 88 | /// Additional mongod CLI arguments. 89 | /// 90 | /// 91 | public string[]? AdditionalArguments { get; set; } 92 | 93 | /// 94 | /// Maximum timespan to wait for mongod process to be ready to accept connections. 95 | /// 96 | /// The timeout cannot be negative. 97 | public TimeSpan ConnectionTimeout 98 | { 99 | get => this._connectionTimeout; 100 | set => this._connectionTimeout = value >= TimeSpan.Zero ? value : throw new ArgumentOutOfRangeException(nameof(this.ConnectionTimeout)); 101 | } 102 | 103 | /// 104 | /// Whether to create a single node replica set or use a standalone mongod instance. 105 | /// 106 | public bool UseSingleNodeReplicaSet { get; set; } 107 | 108 | /// 109 | /// Maximum timespan to wait for the replica set to accept database writes. 110 | /// 111 | /// The timeout cannot be negative. 112 | public TimeSpan ReplicaSetSetupTimeout 113 | { 114 | get => this._replicaSetSetupTimeout; 115 | set => this._replicaSetSetupTimeout = value >= TimeSpan.Zero ? value : throw new ArgumentOutOfRangeException(nameof(this.ReplicaSetSetupTimeout)); 116 | } 117 | 118 | /// 119 | /// A delegate that provides access to any MongodDB-related process standard output. 120 | /// 121 | public Logger? StandardOutputLogger { get; set; } 122 | 123 | /// 124 | /// A delegate that provides access to any MongodDB-related process error output. 125 | /// 126 | public Logger? StandardErrorLogger { get; set; } 127 | 128 | /// 129 | /// The mongod port to use. If not specified, a random available port will be used. 130 | /// 131 | /// The port must be greater than zero. 132 | public int? MongoPort 133 | { 134 | get => this._mongoPort; 135 | set => this._mongoPort = value is not <= 0 ? value : throw new ArgumentOutOfRangeException(nameof(this.MongoPort)); 136 | } 137 | 138 | /// 139 | /// The lifetime of data directories that are automatically created when they are not specified by the user. 140 | /// When their age exceeds this value, they will be deleted on the next run of MongoRunner. 141 | /// 142 | /// The lifetime cannot be negative. 143 | public TimeSpan? DataDirectoryLifetime 144 | { 145 | get => this._dataDirectoryLifetime; 146 | set => this._dataDirectoryLifetime = value is not null && value >= TimeSpan.Zero ? value.Value : throw new ArgumentOutOfRangeException(nameof(this.DataDirectoryLifetime)); 147 | } 148 | 149 | /// 150 | /// The HTTP transport to use for downloading MongoDB binaries and MongoDB release information. 151 | /// 152 | /// 153 | public HttpTransport Transport 154 | { 155 | get => this._httpTransport; 156 | set => this._httpTransport = value ?? throw new ArgumentNullException(nameof(this.Transport)); 157 | } 158 | 159 | /// 160 | /// The maximum timespan to wait before checking for a newer version of MongoDB binaries. 161 | /// 162 | /// The timeout cannot be negative. 163 | public TimeSpan NewVersionCheckTimeout 164 | { 165 | get => this._newVersionCheckTimeout; 166 | set => this._newVersionCheckTimeout = value >= TimeSpan.Zero ? value : throw new ArgumentOutOfRangeException(nameof(this.NewVersionCheckTimeout)); 167 | } 168 | 169 | // Internal properties start here 170 | internal string ReplicaSetName { get; set; } = "singleNodeReplSet"; 171 | 172 | // Useful for testing data directories cleanup 173 | internal string? RootDataDirectoryPath { get; set; } 174 | 175 | private static Exception? CheckDirectoryPathFormat(string? path) 176 | { 177 | if (path == null) 178 | { 179 | return new ArgumentNullException(nameof(path)); 180 | } 181 | 182 | try 183 | { 184 | _ = new DirectoryInfo(path); 185 | } 186 | catch (Exception ex) 187 | { 188 | return ex; 189 | } 190 | 191 | return null; 192 | } 193 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/MongoRunnerPool.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics.CodeAnalysis; 2 | 3 | namespace EphemeralMongo; 4 | 5 | [Experimental("EMEX0001")] 6 | [SuppressMessage("Maintainability", "CA1513", Justification = "ObjectDisposedException.ThrowIf isn't worth it when multi-targeting")] 7 | public sealed class MongoRunnerPool : IDisposable 8 | { 9 | private readonly Guid _id; 10 | private readonly MongoRunnerOptions _options; 11 | private readonly int _maxRentalsPerRunner; 12 | private readonly SemaphoreSlim _mutex = new SemaphoreSlim(1, 1); 13 | private readonly HashSet _runners = []; 14 | private int _isDisposed; 15 | 16 | public MongoRunnerPool(MongoRunnerOptions options, int maxRentalsPerRunner = 100) 17 | { 18 | this._id = Guid.NewGuid(); 19 | this._options = options ?? throw new ArgumentNullException(nameof(options)); 20 | this._maxRentalsPerRunner = maxRentalsPerRunner < 1 21 | ? throw new ArgumentOutOfRangeException(nameof(maxRentalsPerRunner), "Maximum rentals per runner must be greater than 0") 22 | : maxRentalsPerRunner; 23 | } 24 | 25 | public async Task RentAsync(CancellationToken cancellationToken = default) 26 | { 27 | return await this.RentInternalAsync(cancellationToken).ConfigureAwait(false); 28 | } 29 | 30 | private async Task RentInternalAsync(CancellationToken cancellationToken) 31 | { 32 | if (Interlocked.CompareExchange(ref this._isDisposed, 0, 0) == 1) 33 | { 34 | throw new ObjectDisposedException(nameof(MongoRunnerPool)); 35 | } 36 | 37 | await this._mutex.WaitAsync(cancellationToken).ConfigureAwait(false); 38 | 39 | try 40 | { 41 | if (this._runners.FirstOrDefault(r => r.TotalRentals < this._maxRentalsPerRunner) is { } availableRunner) 42 | { 43 | availableRunner.TotalRentals++; 44 | return new PooledMongoRunner(availableRunner); 45 | } 46 | 47 | var underlyingRunner = await MongoRunner.RunAsync(this._options, cancellationToken).ConfigureAwait(false); 48 | var runnerInfo = new PooledMongoRunnerInfo(underlyingRunner, this._id); 49 | this._runners.Add(runnerInfo); 50 | 51 | return new PooledMongoRunner(runnerInfo); 52 | } 53 | finally 54 | { 55 | this._mutex.Release(); 56 | } 57 | } 58 | 59 | public IMongoRunner Rent(CancellationToken cancellationToken = default) 60 | { 61 | return this.RentAsync(cancellationToken).ConfigureAwait(false).GetAwaiter().GetResult(); 62 | } 63 | 64 | public void Return(IMongoRunner runner) 65 | { 66 | if (runner == null) 67 | { 68 | throw new ArgumentNullException(nameof(runner)); 69 | } 70 | 71 | if (Interlocked.CompareExchange(ref this._isDisposed, 0, 0) == 1) 72 | { 73 | throw new ObjectDisposedException(nameof(MongoRunnerPool)); 74 | } 75 | 76 | if (runner is not PooledMongoRunner pooledRunner) 77 | { 78 | throw new ArgumentException("The returned runner was not pooled", nameof(runner)); 79 | } 80 | 81 | if (pooledRunner.Info.ParentPoolId != this._id) 82 | { 83 | throw new ArgumentException("The returned runner was not rented from this pool", nameof(runner)); 84 | } 85 | 86 | this.ReturnInternal(pooledRunner); 87 | } 88 | 89 | private void ReturnInternal(PooledMongoRunner pooledRunner) 90 | { 91 | this._mutex.Wait(); 92 | 93 | var disposeUnderlyingRunner = false; 94 | 95 | try 96 | { 97 | if (!pooledRunner.Info.RentedBy.Remove(pooledRunner.Id)) 98 | { 99 | // already returned 100 | return; 101 | } 102 | 103 | if (pooledRunner.Info.RentedBy.Count == 0 || pooledRunner.Info.TotalRentals >= this._maxRentalsPerRunner) 104 | { 105 | disposeUnderlyingRunner = this._runners.Remove(pooledRunner.Info); 106 | } 107 | } 108 | finally 109 | { 110 | this._mutex.Release(); 111 | } 112 | 113 | if (disposeUnderlyingRunner) 114 | { 115 | pooledRunner.Info.UnderlyingRunner.Dispose(); 116 | } 117 | } 118 | 119 | public void Dispose() 120 | { 121 | if (Interlocked.CompareExchange(ref this._isDisposed, 1, 0) == 1) 122 | { 123 | return; 124 | } 125 | 126 | List? runnersToDispose; 127 | 128 | this._mutex.Wait(); 129 | 130 | try 131 | { 132 | runnersToDispose = [.. this._runners]; 133 | this._runners.Clear(); 134 | } 135 | finally 136 | { 137 | this._mutex.Release(); 138 | } 139 | 140 | if (runnersToDispose.Count > 0) 141 | { 142 | foreach (var runner in runnersToDispose) 143 | { 144 | try 145 | { 146 | runner.UnderlyingRunner.Dispose(); 147 | } 148 | catch 149 | { 150 | // ignore 151 | } 152 | } 153 | 154 | try 155 | { 156 | this._mutex.Dispose(); 157 | } 158 | catch 159 | { 160 | // ignore 161 | } 162 | } 163 | else 164 | { 165 | this._mutex.Dispose(); 166 | } 167 | } 168 | 169 | private sealed class PooledMongoRunnerInfo(IMongoRunner underlyingRunner, Guid parentPoolId) 170 | { 171 | public IMongoRunner UnderlyingRunner { get; } = underlyingRunner; 172 | 173 | public Guid ParentPoolId { get; } = parentPoolId; 174 | 175 | public int TotalRentals { get; set; } = 1; 176 | 177 | public HashSet RentedBy { get; } = []; 178 | } 179 | 180 | private sealed class PooledMongoRunner : IMongoRunner 181 | { 182 | public PooledMongoRunner(PooledMongoRunnerInfo info) 183 | { 184 | this.Id = Guid.NewGuid(); 185 | this.Info = info; 186 | 187 | info.RentedBy.Add(this.Id); 188 | } 189 | 190 | public Guid Id { get; } 191 | 192 | public PooledMongoRunnerInfo Info { get; } 193 | 194 | public string ConnectionString => this.Info.UnderlyingRunner.ConnectionString; 195 | 196 | public Task ImportAsync(string database, string collection, string inputFilePath, string[]? additionalArguments = null, bool drop = false, CancellationToken cancellationToken = default) 197 | { 198 | return this.Info.UnderlyingRunner.ImportAsync(database, collection, inputFilePath, additionalArguments, drop, cancellationToken); 199 | } 200 | 201 | public void Import(string database, string collection, string inputFilePath, string[]? additionalArguments = null, bool drop = false, CancellationToken cancellationToken = default) 202 | { 203 | this.Info.UnderlyingRunner.Import(database, collection, inputFilePath, additionalArguments, drop, cancellationToken); 204 | } 205 | 206 | public Task ExportAsync(string database, string collection, string outputFilePath, string[]? additionalArguments = null, CancellationToken cancellationToken = default) 207 | { 208 | return this.Info.UnderlyingRunner.ExportAsync(database, collection, outputFilePath, additionalArguments, cancellationToken); 209 | } 210 | 211 | public void Export(string database, string collection, string outputFilePath, string[]? additionalArguments = null, CancellationToken cancellationToken = default) 212 | { 213 | this.Info.UnderlyingRunner.Export(database, collection, outputFilePath, additionalArguments, cancellationToken); 214 | } 215 | 216 | public void Dispose() 217 | { 218 | // Prevent end-users from disposing the underlying runner, as this could impact other rentals. 219 | // Let the pool manage the disposal of runners. 220 | } 221 | } 222 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/MongoVersion.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics.CodeAnalysis; 2 | 3 | namespace EphemeralMongo; 4 | 5 | [SuppressMessage("Design", "CA1008:Enums should have zero value", Justification = "Doesn't make sense in this context")] 6 | public enum MongoVersion 7 | { 8 | V6 = 6, 9 | V7 = 7, 10 | V8 = 8, 11 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/MongodProcess.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.Diagnostics; 3 | using System.Diagnostics.CodeAnalysis; 4 | using System.Globalization; 5 | using System.Text; 6 | using System.Text.Json; 7 | using MongoDB.Bson; 8 | using MongoDB.Driver; 9 | using MongoDB.Driver.Core.Events; 10 | using MongoDB.Driver.Core.Servers; 11 | 12 | namespace EphemeralMongo; 13 | 14 | internal sealed class MongodProcess : BaseMongoProcess 15 | { 16 | private const string ConnectionReadySentence = "waiting for connections"; 17 | 18 | // https://github.com/search?q=%22STATUS_DLL_NOT_FOUND%22+%223221225781%22&type=code 19 | [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "STATUS_DLL_NOT_FOUND is a constant from the Windows API")] 20 | private const uint STATUS_DLL_NOT_FOUND = 3221225781; // "-1073741515" as a signed int returned by Process.ExitCode 21 | 22 | private readonly StringBuilder _startupErrors = new StringBuilder(); 23 | 24 | public MongodProcess(MongoRunnerOptions options, string executablePath, string[] arguments) 25 | : base(options, executablePath, arguments) 26 | { 27 | } 28 | 29 | public override async Task StartAsync(CancellationToken cancellationToken) 30 | { 31 | this.Process.OutputDataReceived += this.OnOutputDataReceivedCaptureStartupErrors; 32 | this.Process.ErrorDataReceived += this.OnErrorDataReceivedCaptureStartupErrors; 33 | 34 | try 35 | { 36 | await this.StartAndWaitForConnectionReadinessAsync(cancellationToken).ConfigureAwait(false); 37 | 38 | if (this.Options.UseSingleNodeReplicaSet) 39 | { 40 | await this.ConfigureAndWaitForReplicaSetReadinessAsync(cancellationToken).ConfigureAwait(false); 41 | } 42 | } 43 | finally 44 | { 45 | this.Process.OutputDataReceived -= this.OnOutputDataReceivedCaptureStartupErrors; 46 | this.Process.ErrorDataReceived -= this.OnErrorDataReceivedCaptureStartupErrors; 47 | 48 | this._startupErrors.Clear(); 49 | } 50 | } 51 | 52 | private async Task StartAndWaitForConnectionReadinessAsync(CancellationToken cancellationToken) 53 | { 54 | var isReadyToAcceptConnectionsTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); 55 | 56 | void OnOutputDataReceivedForConnectionReadiness(object sender, DataReceivedEventArgs args) 57 | { 58 | #if NETSTANDARD2_0 59 | var isReadyToAcceptConnections = args.Data != null && args.Data.IndexOf(ConnectionReadySentence, StringComparison.OrdinalIgnoreCase) >= 0; 60 | #else 61 | var isReadyToAcceptConnections = args.Data != null && args.Data.Contains(ConnectionReadySentence, StringComparison.OrdinalIgnoreCase); 62 | #endif 63 | if (isReadyToAcceptConnections) 64 | { 65 | isReadyToAcceptConnectionsTcs.TrySetResult(true); 66 | } 67 | } 68 | 69 | void OnProcessExited(object? sender, EventArgs e) 70 | { 71 | isReadyToAcceptConnectionsTcs.TrySetResult(false); 72 | } 73 | 74 | this.Process.OutputDataReceived += OnOutputDataReceivedForConnectionReadiness; 75 | this.Process.Exited += OnProcessExited; 76 | 77 | try 78 | { 79 | await this.Process.StartProcessWithRetryAsync(cancellationToken).ConfigureAwait(false); 80 | 81 | this.Process.BeginOutputReadLine(); 82 | this.Process.BeginErrorReadLine(); 83 | 84 | using (var timeoutCts = new CancellationTokenSource(this.Options.ConnectionTimeout)) 85 | using (var combinedCts = CancellationTokenSource.CreateLinkedTokenSource(timeoutCts.Token, cancellationToken)) 86 | using (combinedCts.Token.Register(() => isReadyToAcceptConnectionsTcs.TrySetCanceled(combinedCts.Token))) 87 | { 88 | try 89 | { 90 | await isReadyToAcceptConnectionsTcs.Task.ConfigureAwait(false); 91 | } 92 | catch (OperationCanceledException ex) when (timeoutCts.IsCancellationRequested) 93 | { 94 | var timeoutMessage = string.Format( 95 | CultureInfo.InvariantCulture, 96 | "MongoDB connection availability took longer than the specified timeout of {0} seconds. Consider increasing the value of '{1}'.", 97 | this.Options.ConnectionTimeout.TotalSeconds, 98 | nameof(this.Options.ConnectionTimeout)); 99 | 100 | throw new TimeoutException(timeoutMessage, ex); 101 | } 102 | 103 | this.HandleUnexpectedProcessExit(); 104 | } 105 | } 106 | finally 107 | { 108 | this.Process.OutputDataReceived -= OnOutputDataReceivedForConnectionReadiness; 109 | this.Process.Exited -= OnProcessExited; 110 | } 111 | } 112 | 113 | private void HandleUnexpectedProcessExit() 114 | { 115 | if (this.Process.HasExited) 116 | { 117 | // WaitForExit ensure that all output is flushed before we throw the exception, 118 | // ensuring we asynchronously capture all standard output and error messages. 119 | this.Process.WaitForExit(); 120 | throw this.CreateExceptionFromUnexpectedProcessExit(); 121 | } 122 | } 123 | 124 | private EphemeralMongoException CreateExceptionFromUnexpectedProcessExit() 125 | { 126 | var exitCode = (uint)this.Process.ExitCode; 127 | var processDescription = $"{this.Process.StartInfo.FileName} {this.Process.StartInfo.Arguments}"; 128 | var startupErrors = this._startupErrors.ToString(); 129 | var startupErrorsMessage = string.IsNullOrWhiteSpace(startupErrors) ? string.Empty : $" Output: {startupErrors}"; 130 | 131 | return exitCode switch 132 | { 133 | 0 => new EphemeralMongoException($"The MongoDB process '{processDescription}' exited unexpectedly.{startupErrorsMessage}"), 134 | 135 | // Happens on Windows for MongoDB Enterprise edition when sasl2.dll is missing 136 | STATUS_DLL_NOT_FOUND => new EphemeralMongoException($"The MongoDB process '{processDescription}' exited unexpectedly with code {exitCode}. This is likely due to a missing DLL.{startupErrorsMessage}"), 137 | 138 | _ => new EphemeralMongoException($"The MongoDB process '{processDescription}' exited unexpectedly with code {exitCode}.{startupErrorsMessage}") 139 | }; 140 | } 141 | 142 | private async Task ConfigureAndWaitForReplicaSetReadinessAsync(CancellationToken cancellationToken) 143 | { 144 | var isReplicaSetReadyTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); 145 | var isTransactionReadyTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); 146 | 147 | void OnProcessExited(object? sender, EventArgs e) 148 | { 149 | isReplicaSetReadyTcs.TrySetResult(false); 150 | isTransactionReadyTcs.TrySetResult(false); 151 | } 152 | 153 | void OnClusterDescriptionChanged(ClusterDescriptionChangedEvent evt) 154 | { 155 | if (evt.NewDescription.Servers.Any(x => x.Type == ServerType.ReplicaSetPrimary && x.State == ServerState.Connected)) 156 | { 157 | isReplicaSetReadyTcs.TrySetResult(true); 158 | } 159 | 160 | if (evt.NewDescription.Servers.Any(x => x.State == ServerState.Connected && x.IsDataBearing)) 161 | { 162 | isTransactionReadyTcs.TrySetResult(true); 163 | } 164 | } 165 | 166 | this.Process.Exited += OnProcessExited; 167 | 168 | try 169 | { 170 | var settings = new MongoClientSettings 171 | { 172 | Server = new MongoServerAddress("127.0.0.1", this.Options.MongoPort!.Value), 173 | ReplicaSetName = this.Options.ReplicaSetName, 174 | DirectConnection = true, 175 | ClusterConfigurator = builder => 176 | { 177 | builder.Subscribe(OnClusterDescriptionChanged); 178 | } 179 | }; 180 | 181 | var client = new MongoClient(settings); 182 | var admin = client.GetDatabase("admin"); 183 | 184 | var replConfig = new BsonDocument(new List 185 | { 186 | new BsonElement("_id", this.Options.ReplicaSetName), 187 | new BsonElement("members", new BsonArray 188 | { 189 | new BsonDocument 190 | { 191 | { "_id", 0 }, 192 | { "host", string.Format(CultureInfo.InvariantCulture, "127.0.0.1:{0}", this.Options.MongoPort) } 193 | }, 194 | }), 195 | }); 196 | 197 | using (var timeoutCts = new CancellationTokenSource(this.Options.ReplicaSetSetupTimeout)) 198 | using (var combinedCts = CancellationTokenSource.CreateLinkedTokenSource(timeoutCts.Token, cancellationToken)) 199 | using (combinedCts.Token.Register(() => 200 | { 201 | isReplicaSetReadyTcs.TrySetCanceled(combinedCts.Token); 202 | isTransactionReadyTcs.TrySetCanceled(combinedCts.Token); 203 | })) 204 | { 205 | var command = new BsonDocument("replSetInitiate", replConfig); 206 | 207 | try 208 | { 209 | await admin.RunCommandAsync(command, cancellationToken: combinedCts.Token).ConfigureAwait(false); 210 | } 211 | catch (OperationCanceledException) when (timeoutCts.IsCancellationRequested) 212 | { 213 | var timeoutMessage = string.Format( 214 | CultureInfo.InvariantCulture, 215 | "Replica set initialization command took longer than the specified timeout of {0} seconds. Consider increasing the value of '{1}'.", 216 | this.Options.ReplicaSetSetupTimeout.TotalSeconds, 217 | nameof(this.Options.ReplicaSetSetupTimeout)); 218 | 219 | throw new TimeoutException(timeoutMessage); 220 | } 221 | 222 | try 223 | { 224 | await isReplicaSetReadyTcs.Task.ConfigureAwait(false); 225 | } 226 | catch (OperationCanceledException) when (timeoutCts.IsCancellationRequested) 227 | { 228 | var timeoutMessage = string.Format( 229 | CultureInfo.InvariantCulture, 230 | "Replica set initialization took longer than the specified timeout of {0} seconds. Consider increasing the value of '{1}'.", 231 | this.Options.ReplicaSetSetupTimeout.TotalSeconds, 232 | nameof(this.Options.ReplicaSetSetupTimeout)); 233 | 234 | throw new TimeoutException(timeoutMessage); 235 | } 236 | 237 | try 238 | { 239 | await isTransactionReadyTcs.Task.ConfigureAwait(false); 240 | } 241 | catch (OperationCanceledException) when (timeoutCts.IsCancellationRequested) 242 | { 243 | var timeoutMessage = string.Format( 244 | CultureInfo.InvariantCulture, 245 | "Cluster readiness for transactions took longer than the specified timeout of {0} seconds. Consider increasing the value of '{1}'.", 246 | this.Options.ReplicaSetSetupTimeout.TotalSeconds, 247 | nameof(this.Options.ReplicaSetSetupTimeout)); 248 | 249 | throw new TimeoutException(timeoutMessage); 250 | } 251 | 252 | this.HandleUnexpectedProcessExit(); 253 | } 254 | } 255 | finally 256 | { 257 | this.Process.Exited -= OnProcessExited; 258 | } 259 | } 260 | 261 | private void OnOutputDataReceivedCaptureStartupErrors(object sender, DataReceivedEventArgs args) 262 | { 263 | if (args.Data == null) 264 | { 265 | return; 266 | } 267 | 268 | try 269 | { 270 | // Here's the kind of document we're trying to parse: 271 | // { 272 | // "t": { 273 | // "$date": "2025-04-18T22:15:02.064-04:00" 274 | // }, 275 | // "s": "E", 276 | // "c": "CONTROL", 277 | // "id": 20568, 278 | // "ctx": "initandlisten", 279 | // "msg": "Error setting up listener", 280 | // "attr": { 281 | // "error": { 282 | // "code": 9001, 283 | // "codeName": "SocketException", 284 | // "errmsg": "127.0.0.1:58905 :: caused by :: setup bind :: caused by :: An attempt was made to access a socket in a way forbidden by its access permissions." 285 | // } 286 | // } 287 | // } 288 | using var document = JsonDocument.Parse(args.Data); 289 | 290 | if (document.RootElement.TryGetProperty("s", out var sevEl) && sevEl.ValueKind == JsonValueKind.String && sevEl.GetString() is "E" or "F") 291 | { 292 | this._startupErrors.AppendLine(args.Data); 293 | } 294 | } 295 | catch 296 | { 297 | // Startup error messages (like invalid arguments) are also sent to standard output in plain text, not as structured JSON 298 | this._startupErrors.AppendLine(args.Data); 299 | } 300 | } 301 | 302 | private void OnErrorDataReceivedCaptureStartupErrors(object sender, DataReceivedEventArgs args) 303 | { 304 | if (args.Data != null) 305 | { 306 | this._startupErrors.AppendLine(args.Data); 307 | } 308 | } 309 | } 310 | 311 | file static class ProcessExtensions 312 | { 313 | [SuppressMessage("Usage", "CA2249:Consider using \'string.Contains\' instead of \'string.IndexOf\'", Justification = "Not worth it due to multi-targeting")] 314 | public static async Task StartProcessWithRetryAsync(this Process process, CancellationToken cancellationToken) 315 | { 316 | const int maxAttempts = 3; 317 | const int retryDelayMs = 50; 318 | 319 | for (var attempt = 1; attempt <= maxAttempts; attempt++) 320 | { 321 | try 322 | { 323 | process.Start(); 324 | return; 325 | } 326 | // This exception rarely happens on Linux in CI during tests with high concurrency 327 | // System.ComponentModel.Win32Exception : An error occurred trying to start process '/mongod' with working directory ''. Text file busy 328 | catch (Win32Exception ex) when (ex.Message.IndexOf("text file busy", StringComparison.OrdinalIgnoreCase) >= 0) 329 | { 330 | if (attempt == maxAttempts) 331 | { 332 | throw; 333 | } 334 | 335 | await Task.Delay(retryDelayMs, cancellationToken).ConfigureAwait(false); 336 | } 337 | } 338 | } 339 | } 340 | -------------------------------------------------------------------------------- /src/EphemeralMongo/NativeMethods.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.Diagnostics; 3 | using System.Diagnostics.CodeAnalysis; 4 | using System.Runtime.InteropServices; 5 | using Windows.Win32; 6 | using Windows.Win32.Security; 7 | using Windows.Win32.System.JobObjects; 8 | using Microsoft.Win32.SafeHandles; 9 | 10 | namespace EphemeralMongo; 11 | 12 | [SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "We ensure this runs on Windows")] 13 | internal static class NativeMethods 14 | { 15 | private static readonly object CreateJobObjectLock = new object(); 16 | private static SafeFileHandle? _jobObjectHandle; 17 | 18 | public static void EnsureMongoProcessesAreKilledWhenCurrentProcessIsKilled() 19 | { 20 | // We only support this feature on Windows and modern .NET (netcoreapp3.1, net5.0, net6.0, net7.0 and so on): 21 | // - Job objects are Windows-specific 22 | // - On .NET Framework, the current process crashes even if we don't dispose the job object handle (tested with in test project while running "dotnet test") 23 | // 24 | // "A job object allows groups of processes to be managed as a unit. 25 | // Operations performed on a job object affect all processes associated with the job object. 26 | // Examples include [...] or terminating all processes associated with a job." 27 | // See: https://learn.microsoft.com/en-us/windows/win32/procthread/job-objects 28 | if (IsWindows() && !IsNetFramework()) 29 | { 30 | CreateSingletonJobObject(); 31 | } 32 | } 33 | 34 | private static bool IsWindows() => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); 35 | 36 | // This way of detecting if running on .NET Framework is also used in .NET runtime tests, see: 37 | // https://github.com/dotnet/runtime/blob/v6.0.0/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.Windows.cs#L21 38 | private static bool IsNetFramework() => RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework", StringComparison.OrdinalIgnoreCase); 39 | 40 | private static unsafe void CreateSingletonJobObject() 41 | { 42 | // Using a static job object ensures there's a single job object created for the current process. 43 | // Any MongoDB-related process that we will be created later on will be associated to the current process through this job object. 44 | // If the current process dies prematurely, all MongoDB-related processes will also be killed. 45 | // However, we never dispose this job object handle otherwise it would immediately kill the current process too. 46 | if (_jobObjectHandle != null) 47 | { 48 | return; 49 | } 50 | 51 | lock (CreateJobObjectLock) 52 | { 53 | if (_jobObjectHandle != null) 54 | { 55 | return; 56 | } 57 | 58 | // https://www.meziantou.net/killing-all-child-processes-when-the-parent-exits-job-object.htm 59 | var attributes = new SECURITY_ATTRIBUTES 60 | { 61 | bInheritHandle = false, 62 | lpSecurityDescriptor = IntPtr.Zero.ToPointer(), 63 | nLength = (uint)Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES)), 64 | }; 65 | 66 | SafeFileHandle? jobHandle = null; 67 | 68 | try 69 | { 70 | jobHandle = PInvoke.CreateJobObject(attributes, lpName: null); 71 | 72 | if (jobHandle.IsInvalid) 73 | { 74 | throw new Win32Exception(Marshal.GetLastWin32Error()); 75 | } 76 | 77 | // Configure the job object to kill all child processes when the root process is killed 78 | var info = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION 79 | { 80 | BasicLimitInformation = new JOBOBJECT_BASIC_LIMIT_INFORMATION 81 | { 82 | // Kill all processes associated to the job when the last handle is closed 83 | LimitFlags = JOB_OBJECT_LIMIT.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, 84 | }, 85 | }; 86 | 87 | if (!PInvoke.SetInformationJobObject(jobHandle, JOBOBJECTINFOCLASS.JobObjectExtendedLimitInformation, &info, (uint)Marshal.SizeOf())) 88 | { 89 | throw new Win32Exception(Marshal.GetLastWin32Error()); 90 | } 91 | 92 | // Assign the job object to the current process 93 | if (!PInvoke.AssignProcessToJobObject(jobHandle, Process.GetCurrentProcess().SafeHandle)) 94 | { 95 | throw new Win32Exception(Marshal.GetLastWin32Error()); 96 | } 97 | 98 | _jobObjectHandle = jobHandle; 99 | } 100 | catch 101 | { 102 | // It's safe to dispose the job object handle here because it was not yet associated to the current process 103 | jobHandle?.Dispose(); 104 | throw; 105 | } 106 | } 107 | } 108 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/NativeMethods.txt: -------------------------------------------------------------------------------- 1 | CreateJobObject 2 | SetInformationJobObject 3 | AssignProcessToJobObject 4 | JOBOBJECT_EXTENDED_LIMIT_INFORMATION -------------------------------------------------------------------------------- /src/EphemeralMongo/PortFactory.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using System.Net.Sockets; 3 | 4 | namespace EphemeralMongo; 5 | 6 | internal sealed class PortFactory : IPortFactory 7 | { 8 | public int GetRandomAvailablePort() 9 | { 10 | var listener = new TcpListener(IPAddress.Loopback, port: 0); 11 | listener.Start(); 12 | var port = ((IPEndPoint)listener.LocalEndpoint).Port; 13 | listener.Stop(); 14 | return port; 15 | } 16 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/ProcessArgument.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | 3 | namespace EphemeralMongo; 4 | 5 | internal static class ProcessArgument 6 | { 7 | private const char DoubleQuote = '"'; 8 | private const char Backslash = '\\'; 9 | 10 | // Inspired from https://github.com/dotnet/runtime/blob/v6.0.0/src/libraries/System.Private.CoreLib/src/System/PasteArguments.cs 11 | public static string Escape(string path) 12 | { 13 | // Path does not need to be escaped 14 | if (path.Length != 0 && path.All(c => !char.IsWhiteSpace(c) && c != DoubleQuote)) 15 | { 16 | return path; 17 | } 18 | 19 | var stringBuilder = new StringBuilder(); 20 | 21 | stringBuilder.Append(DoubleQuote); 22 | 23 | for (var i = 0; i < path.Length;) 24 | { 25 | var c = path[i++]; 26 | 27 | if (c == Backslash) 28 | { 29 | var backslashCount = 1; 30 | while (i < path.Length && path[i] == Backslash) 31 | { 32 | backslashCount++; 33 | i++; 34 | } 35 | 36 | if (i == path.Length) 37 | { 38 | stringBuilder.Append(Backslash, backslashCount * 2); 39 | } 40 | else if (path[i] == DoubleQuote) 41 | { 42 | stringBuilder.Append(Backslash, backslashCount * 2 + 1).Append(DoubleQuote); 43 | i++; 44 | } 45 | else 46 | { 47 | stringBuilder.Append(Backslash, backslashCount); 48 | } 49 | } 50 | else if (c == DoubleQuote) 51 | { 52 | stringBuilder.Append(Backslash).Append(DoubleQuote); 53 | } 54 | else 55 | { 56 | stringBuilder.Append(c); 57 | } 58 | } 59 | 60 | stringBuilder.Append(DoubleQuote); 61 | 62 | return stringBuilder.ToString(); 63 | } 64 | } -------------------------------------------------------------------------------- /src/EphemeralMongo/PublicAPI.Shipped.txt: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | EphemeralMongo.EphemeralMongoException 3 | EphemeralMongo.EphemeralMongoException.EphemeralMongoException(string! message) -> void 4 | EphemeralMongo.EphemeralMongoException.EphemeralMongoException(string! message, System.Exception! innerException) -> void 5 | EphemeralMongo.HttpTransport 6 | EphemeralMongo.HttpTransport.HttpTransport(System.Net.Http.HttpClient! httpClient) -> void 7 | EphemeralMongo.HttpTransport.HttpTransport(System.Net.Http.HttpMessageHandler! handler) -> void 8 | EphemeralMongo.IMongoRunner 9 | EphemeralMongo.IMongoRunner.ConnectionString.get -> string! 10 | EphemeralMongo.IMongoRunner.Export(string! database, string! collection, string! outputFilePath, string![]? additionalArguments = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> void 11 | EphemeralMongo.IMongoRunner.ExportAsync(string! database, string! collection, string! outputFilePath, string![]? additionalArguments = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! 12 | EphemeralMongo.IMongoRunner.Import(string! database, string! collection, string! inputFilePath, string![]? additionalArguments = null, bool drop = false, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> void 13 | EphemeralMongo.IMongoRunner.ImportAsync(string! database, string! collection, string! inputFilePath, string![]? additionalArguments = null, bool drop = false, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! 14 | EphemeralMongo.Logger 15 | EphemeralMongo.MongoEdition 16 | EphemeralMongo.MongoEdition.Community = 0 -> EphemeralMongo.MongoEdition 17 | EphemeralMongo.MongoEdition.Enterprise = 1 -> EphemeralMongo.MongoEdition 18 | EphemeralMongo.MongoRunner 19 | EphemeralMongo.MongoRunnerOptions 20 | EphemeralMongo.MongoRunnerOptions.AdditionalArguments.get -> string![]? 21 | EphemeralMongo.MongoRunnerOptions.AdditionalArguments.set -> void 22 | EphemeralMongo.MongoRunnerOptions.BinaryDirectory.get -> string? 23 | EphemeralMongo.MongoRunnerOptions.BinaryDirectory.set -> void 24 | EphemeralMongo.MongoRunnerOptions.ConnectionTimeout.get -> System.TimeSpan 25 | EphemeralMongo.MongoRunnerOptions.ConnectionTimeout.set -> void 26 | EphemeralMongo.MongoRunnerOptions.DataDirectory.get -> string? 27 | EphemeralMongo.MongoRunnerOptions.DataDirectory.set -> void 28 | EphemeralMongo.MongoRunnerOptions.DataDirectoryLifetime.get -> System.TimeSpan? 29 | EphemeralMongo.MongoRunnerOptions.DataDirectoryLifetime.set -> void 30 | EphemeralMongo.MongoRunnerOptions.Edition.get -> EphemeralMongo.MongoEdition 31 | EphemeralMongo.MongoRunnerOptions.Edition.set -> void 32 | EphemeralMongo.MongoRunnerOptions.MongoPort.get -> int? 33 | EphemeralMongo.MongoRunnerOptions.MongoPort.set -> void 34 | EphemeralMongo.MongoRunnerOptions.MongoRunnerOptions() -> void 35 | EphemeralMongo.MongoRunnerOptions.NewVersionCheckTimeout.get -> System.TimeSpan 36 | EphemeralMongo.MongoRunnerOptions.NewVersionCheckTimeout.set -> void 37 | EphemeralMongo.MongoRunnerOptions.ReplicaSetSetupTimeout.get -> System.TimeSpan 38 | EphemeralMongo.MongoRunnerOptions.ReplicaSetSetupTimeout.set -> void 39 | EphemeralMongo.MongoRunnerOptions.StandardErrorLogger.get -> EphemeralMongo.Logger? 40 | EphemeralMongo.MongoRunnerOptions.StandardErrorLogger.set -> void 41 | EphemeralMongo.MongoRunnerOptions.StandardOutputLogger.get -> EphemeralMongo.Logger? 42 | EphemeralMongo.MongoRunnerOptions.StandardOutputLogger.set -> void 43 | EphemeralMongo.MongoRunnerOptions.Transport.get -> EphemeralMongo.HttpTransport! 44 | EphemeralMongo.MongoRunnerOptions.Transport.set -> void 45 | EphemeralMongo.MongoRunnerOptions.UseSingleNodeReplicaSet.get -> bool 46 | EphemeralMongo.MongoRunnerOptions.UseSingleNodeReplicaSet.set -> void 47 | EphemeralMongo.MongoRunnerOptions.Version.get -> EphemeralMongo.MongoVersion 48 | EphemeralMongo.MongoRunnerOptions.Version.set -> void 49 | EphemeralMongo.MongoVersion 50 | EphemeralMongo.MongoVersion.V6 = 6 -> EphemeralMongo.MongoVersion 51 | EphemeralMongo.MongoVersion.V7 = 7 -> EphemeralMongo.MongoVersion 52 | EphemeralMongo.MongoVersion.V8 = 8 -> EphemeralMongo.MongoVersion 53 | static EphemeralMongo.MongoRunner.Run(EphemeralMongo.MongoRunnerOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> EphemeralMongo.IMongoRunner! 54 | static EphemeralMongo.MongoRunner.RunAsync(EphemeralMongo.MongoRunnerOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! 55 | -------------------------------------------------------------------------------- /src/EphemeralMongo/PublicAPI.Unshipped.txt: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | EphemeralMongo.MongoRunnerPool 3 | EphemeralMongo.MongoRunnerPool.Dispose() -> void 4 | EphemeralMongo.MongoRunnerPool.MongoRunnerPool(EphemeralMongo.MongoRunnerOptions! options, int maxRentalsPerRunner = 100) -> void 5 | EphemeralMongo.MongoRunnerPool.Rent(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> EphemeralMongo.IMongoRunner! 6 | EphemeralMongo.MongoRunnerPool.RentAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! 7 | EphemeralMongo.MongoRunnerPool.Return(EphemeralMongo.IMongoRunner! runner) -> void 8 | -------------------------------------------------------------------------------- /src/EphemeralMongo/TimeProvider.cs: -------------------------------------------------------------------------------- 1 | namespace EphemeralMongo; 2 | 3 | internal sealed class TimeProvider : ITimeProvider 4 | { 5 | public DateTimeOffset UtcNow => DateTimeOffset.UtcNow; 6 | } --------------------------------------------------------------------------------