LocalDependencyCache is a C# Azure Functions solution that builds a compact SQLite cache of the most popular PowerShell Gallery packages and publishes that cache as a downloadable artifact.
The intended flow is:
- The Azure Function asks the PowerShell Gallery OData
Search()endpoint for the most-downloaded packages (100 by default) and takes the latest stable version of each. - It resolves those packages' dependencies, transitively, to the versions that satisfy their ranges.
- It writes package identity, tags (including
PSCommand_andPSDscResource_), and dependency ranges into a fresh SQLite database. - If the content changed, it compacts the database, packages it into a ZIP artifact (about 0.5 MB for 100 packages), and publishes that ZIP plus a JSON manifest to either:
- Azure Blob Storage, or
- a local filesystem folder for development and test.
- PSResourceGet downloads the published ZIP through Azure Front Door, extracts the SQLite file locally, and performs queries locally. Packages that are not in the cache are looked up in the Gallery as before.
src/LocalDependencyCache.Core- Core cache generation logic
- PowerShell Gallery feed parsing
- SQLite schema creation and data upsert logic
- Artifact publishing abstractions and implementations
src/LocalDependencyCache.Query- Shared query library for cache consumers (including PSResourceGet scenarios)
- Targets
netstandard2.0, so .NET Framework 4.7.2+ (PSResourceGet) and .NET 8 can both reference it; consumers can use any C# version - Read-only SQLite query APIs for name, name + version, tag, DSC resource, command, and package-prefix search
src/LocalDependencyCache.FunctionApp- Azure Functions isolated worker host
- Timer-triggered sync entry point
--run-oncelocal execution path for development
tests/LocalDependencyCache.Tests- Parser tests
- End-to-end local filesystem publish tests
infra- Bicep templates for the Azure resources (Function App, storage, Front Door, monitoring)
ev2/ServiceGroupRoot- Ev2 service model, rollout spec, scope bindings, parameters, compiled ARM template, and the shell script that zip-deploys the Function App
.cici.yml: Azure DevOps CI pipeline (PRs andmain: build, compliance, tests on three OSes)build.yml,test.yml: job templates used by the CI pipeline
.pipelines/LocalDependencyCache.yml- OneBranch official pipeline: builds, signs, and packs
LocalDependencyCache.Query, then optionally publishes it to an Azure Artifacts feed and (after manual validation) NuGet.org. Uses.config/tsaoptions.jsonfor CodeQL/TSA bug filing.
- OneBranch official pipeline: builds, signs, and packs
.pipelines/LocalDependencyCache-AzureFunction.yml- OneBranch official pipeline: builds the Function App and Ev2 specs, then deploys to production with Ev2
The Functions host is configured in src/LocalDependencyCache.FunctionApp/Program.cs.
Key points:
- Uses the Azure Functions isolated worker model.
- Binds configuration into
SyncSettings. - Registers a typed
HttpClientforGalleryClient. - Chooses artifact publishing mode at startup:
FileSystemArtifactStorefor local developmentBlobArtifactStorefor Azure publishing
- Supports
--run-oncefor local execution without relying on a running timer host.
The scheduled function entry point is in src/LocalDependencyCache.FunctionApp/Functions/SyncCacheTimerFunction.cs.
It uses the TimerSchedule setting and delegates all real work to PackageCacheSyncService.
The main orchestration is in src/LocalDependencyCache.Core/PackageCacheSyncService.cs.
Per run, it:
-
Takes the sync lock (
LockBlobName). If another run holds it, the run is skipped without changes. If the lock is lost mid-run, the run stops without publishing. -
Downloads the current
latestartifact, if any, to read its content fingerprint. -
Selects the cache contents with PackageSetBuilder:
- the latest stable version of the
TopPackageCountmost-downloaded packages - when
IncludeDependenciesis on, a version for each dependency, transitively, choosing in order: a version already selected that satisfies the range, the dependency's latest stable version, the highest satisfying stable version, then the highest satisfying prerelease - dependencies with no satisfying version are logged and reported, not cached
Gallery requests retry transient failures (network errors, timeouts, 408, 429, 5xx) with exponential backoff.
- the latest stable version of the
-
Computes a SHA-256 fingerprint of the selected content. If it matches the published cache, the run ends without publishing.
-
Otherwise writes a fresh SQLite database (packages, tags, dependencies, plus
content_hash,generated_utc, andtop_package_countinsync_state), so packages that left the top list are dropped. -
Compacts the database with
PRAGMA optimizeandVACUUM, packages it into a ZIP artifact, and computes a SHA-256 hash for that ZIP. -
Publishes, in this order:
versions/<generated yyyyMMddHHmmss>-<sha256 prefix>/psgallery-cache.zip(never overwritten)latest/psgallery-cache.ziplatest/psgallery-cache.manifest.json(written last, so it always references a complete artifact)
-
Deletes versioned artifacts beyond
RetainVersions.
A failure anywhere before publishing leaves the previously published cache untouched.
The SQLite schema is created in src/LocalDependencyCache.Core/SqlitePackageCache.cs.
Main tables:
packagestagspackage_tagsdependenciessync_state
Supported lookup patterns include:
- package identity search by
IdandVersion - command search via tags prefixed with
PSCommand_ - dependency lookup and NuGet version-range resolution
Use src/LocalDependencyCache.Query from cache consumers to query an existing SQLite cache file without depending on the sync pipeline.
Example:
using LocalDependencyCache.Query;
var client = new SqlitePackageQueryClient(@".artifacts\psgallery-cache.sqlite");
var nameMatches = client.FindByPackageId("Sample.Module");
var versionMatches = client.FindByPackageIdAndVersion("Sample.Module", "1.2.3");
var tagMatches = client.FindByTag("Azure");
var dscMatches = client.FindByDscResourceName("File");
var commandMatches = client.FindByCommandName("Get-Module");
var idPrefixMatches = client.SearchByPackageIdPrefix("Az.", maxResults: 50);
// Dependency resolution
var dependencies = client.GetDependencies("Az.Compute", "1.0.0");
foreach (var dependency in dependencies)
{
var best = client.FindLatestVersionSatisfying(dependency.Id, dependency.VersionRange);
}
var candidates = client.FindVersionsSatisfying("Az.Accounts", "[5.5.5, )", includePrerelease: true);Exact names and tags are ASCII case-insensitive; versions match the stored
string exactly. Searches return all matching cached versions, including
prereleases, sorted by name and then by semantic version (so 1.9.0 precedes
1.10.0-beta, which precedes 1.10.0). SearchByPackageIdPrefix applies its
limit before that sort, in name and version-text order.
GetDependencies returns the raw NuGet range declared for each dependency;
an empty range means any version. FindVersionsSatisfying and
FindLatestVersionSatisfying apply NuGet range semantics (via
NuGet.Versioning) and exclude prereleases unless includePrerelease is set.
Gallery forms such as (, ) are treated as unbounded. Resolution is one level
deep; callers recurse to build a full dependency graph.
Command and DSC-resource searches match PSCommand_ and PSDscResource_ tags.
The cache holds only the most popular packages, so a name or version lookup that finds nothing should fall back to the Gallery. Tag, command, and DSC-resource results cover cached packages only; a missing match does not mean no Gallery package provides it.
Artifact publishing implementations are in src/LocalDependencyCache.Core/ArtifactStores.cs.
FileSystemArtifactStore- Used for local development and tests
- Writes versioned and latest ZIP artifacts under a local folder
BlobArtifactStore- Used for Azure deployment
- Uploads the versioned ZIP with
If-None-Match: *, so a published version is never replaced - Uploads the latest alias, then a JSON manifest with artifact URL, version, hash, and
ETag
Version names are <generated yyyyMMddHHmmss>-<first 12 hex characters of the ZIP's SHA-256>, so a
name always identifies the same bytes. Blob uploads set CDN-friendly headers:
| Blob | Cache-Control |
Content-Type |
|---|---|---|
versions/... |
public, max-age=31536000, immutable |
application/zip |
latest/...zip |
public, max-age=300 |
application/zip |
latest/...manifest.json |
public, max-age=300 |
application/json |
Clients should read the manifest and download artifactUrl (a versioned, cache-forever URL), then verify
sha256. The latest ZIP alias is up to 5 minutes stale behind a CDN.
Example local configuration is in src/LocalDependencyCache.FunctionApp/local.settings.json.example.
Common settings:
TimerSchedule- Azure Functions timer CRON expression; hourly (
0 0 * * * *) is cheap because each run takes seconds
- Azure Functions timer CRON expression; hourly (
PackageCache__GalleryEndpoint- PowerShell Gallery OData endpoint
PackageCache__PageSize- Packages requested per Gallery query (maximum 100)
PackageCache__TopPackageCount- Number of most-downloaded packages to cache (latest stable version of each); defaults to
100
- Number of most-downloaded packages to cache (latest stable version of each); defaults to
PackageCache__IncludeDependencies- Also cache the versions that satisfy the top packages' dependencies, transitively; defaults to
true
- Also cache the versions that satisfy the top packages' dependencies, transitively; defaults to
PackageCache__MaxRetries- Retries per request for transient Gallery failures; defaults to
4
- Retries per request for transient Gallery failures; defaults to
PackageCache__RetryBaseDelayMilliseconds- Base delay for exponential backoff with jitter (capped at one minute); a
Retry-Afterheader takes precedence; defaults to1000
- Base delay for exponential backoff with jitter (capped at one minute); a
PackageCache__StorageModeFileSystemorBlob
PackageCache__OutputDirectory- Local artifact folder used by filesystem mode
PackageCache__DatabaseName- SQLite filename
PackageCache__LatestBlobName- Published latest ZIP path
PackageCache__ManifestBlobName- Published latest manifest path
PackageCache__RetainVersions- Number of versioned artifacts to keep (newest by creation time; the current one is always kept); defaults to
10,0keeps all
- Number of versioned artifacts to keep (newest by creation time; the current one is always kept); defaults to
PackageCache__LockBlobName- Lock used to stop overlapping sync runs; defaults to
locks/psgallery-cache.lock - In Blob mode this blob is leased for the run (60-second lease, renewed every 15 seconds, released at the end; a crashed run's lease expires on its own)
- In FileSystem mode it is an exclusive lock file under
OutputDirectory - A run that cannot take the lock logs a warning and exits without changes
- Lock used to stop overlapping sync runs; defaults to
PackageCache__BlobConnectionString- Blob Storage connection string when using connection-string auth
PackageCache__BlobContainerName- Blob container name
PackageCache__BlobContainerUrl- Container URL when using managed identity
PackageCache__BlobBaseUrl- Public CDN or static-website base URL for manifest artifact links
- .NET SDK 10.0.100 or newer (pinned by global.json; SDK 9.0.200+ is the minimum that can read the
.slnxsolution file) - .NET 8 runtime (the Function App and tests target
net8.0) - Internet access to
https://www.powershellgallery.com
Optional for full Functions-host testing:
- Azure Functions Core Tools
From the repository root:
dotnet test .\LocalDependencyCache.slnxCurrent automated coverage includes:
- Atom feed parsing
- dependency parsing and NuGet version-range resolution
- gallery queries (top packages, latest version, all versions), paging, escaping, and retries
- package selection: top packages, transitive dependency resolution, reuse, prerelease fallback, cycles, unresolved dependencies
- sync: rebuild each run, content fingerprint, skip unchanged, failures leave the published cache untouched
- sync locking (file lock, lease loss, skipped runs)
- artifact publishing: change detection, immutable content-addressed versions, cache headers, retention
- command-tag lookup against generated SQLite
The Blob lease tests are skipped unless LDC_TEST_BLOB_CONNECTION_STRING is set.
To run them against the Azurite emulator:
npx -p azurite azurite-blob --silent --location $env:TEMP\azurite # in a separate terminal
$env:LDC_TEST_BLOB_CONNECTION_STRING = 'UseDevelopmentStorage=true'
dotnet test .\LocalDependencyCache.slnxThis is the fastest local validation path.
Use the built-in one-shot execution mode:
dotnet run --project .\src\LocalDependencyCache.FunctionApp\LocalDependencyCache.FunctionApp.csproj -- --run-onceBy default, local settings use filesystem publishing and write artifacts under:
.artifacts
During development I also validated the same flow with a custom output folder, which produced:
.artifacts-local\latest\psgallery-cache.zip.artifacts-local\latest\psgallery-cache.manifest.json.artifacts-local\versions\<version>\psgallery-cache.zip
After a successful local run, verify that these files exist:
Get-ChildItem .\.artifacts\latest
Get-ChildItem .\.artifacts\versions -RecurseYou can also inspect the manifest:
Get-Content .\.artifacts\latest\psgallery-cache.manifest.jsonAfter a successful run, the working database is typically at:
.artifacts\psgallery-cache.sqlite
The published artifact is typically at:
.artifacts\latest\psgallery-cache.zip
Use one of the methods below.
- Open a terminal in repo root.
- Start sqlite3:
sqlite3 .\.artifacts\psgallery-cache.sqlite- In the sqlite prompt, run:
.tables
.schema packages
.schema tags
.schema dependencies- Run useful inspection queries:
-- Basic row counts
SELECT 'packages' AS table_name, COUNT(*) AS row_count FROM packages
UNION ALL
SELECT 'tags', COUNT(*) FROM tags
UNION ALL
SELECT 'package_tags', COUNT(*) FROM package_tags
UNION ALL
SELECT 'dependencies', COUNT(*) FROM dependencies;
-- Most recently published packages
SELECT package_id, version, datetime(published_unix, 'unixepoch') AS published_utc
FROM packages
WHERE published_unix IS NOT NULL
ORDER BY published_unix DESC
LIMIT 20;
-- Packages that expose a specific command tag
SELECT DISTINCT p.package_id, p.version
FROM tags t
JOIN package_tags pt ON pt.tag_key = t.tag_key
JOIN packages p ON p.package_key = pt.package_key
WHERE t.is_command_tag = 1
AND t.command_name = 'Get-Module'
ORDER BY p.package_id, p.version;
-- Dependencies for a specific package
SELECT p.package_id, p.version, d.dependency_id, d.version_range_raw, d.min_version, d.max_version
FROM dependencies d
JOIN packages p ON p.package_key = d.package_key
WHERE p.package_id = 'Sample.Module'
ORDER BY p.version;
-- Sync state
SELECT state_key, state_value
FROM sync_state
ORDER BY state_key;- Exit sqlite3:
.quitIf you prefer a GUI, open .artifacts\psgallery-cache.sqlite with DB Browser for SQLite or a VS Code SQLite extension.
Suggested first checks:
- Verify
sync_statecontainscontent_hash,generated_utc, andtop_package_count. - Check row counts in
packages,tags, anddependencies. - Run the command-tag lookup query above to confirm
PSCommand_*tags were parsed correctly.
published_unixandupdated_unixare stored as Unix seconds; usedatetime(column, 'unixepoch')to render UTC values in SQLite.- Final dependency compatibility checks should be done in application code using semantic version rules; SQL queries are best used for inspection and candidate filtering.
Use one of the two workflows below.
This is the most reliable local debugging path because it runs the same DI container and sync pipeline as the Function trigger, but executes once and exits.
- Open the repo root in VS Code.
- Verify prerequisites from an integrated terminal:
dotnet --version- Confirm local settings exist at src/LocalDependencyCache.FunctionApp/local.settings.json.
- For local debugging, keep these values in that file:
PackageCache__StorageMode:FileSystemPackageCache__OutputDirectory:.artifactsPackageCache__GalleryEndpoint: a reachable OData endpoint
- Set breakpoints in these files:
- src/LocalDependencyCache.FunctionApp/Program.cs
- src/LocalDependencyCache.Core/PackageCacheSyncService.cs
- src/LocalDependencyCache.Core/GalleryClient.cs
- src/LocalDependencyCache.Core/SqlitePackageCache.cs
- Start debugging from VS Code as a .NET launch and pass this argument:
--run-once
- If you prefer terminal-first debugging, run exactly this command from repo root:
dotnet run --project .\src\LocalDependencyCache.FunctionApp\LocalDependencyCache.FunctionApp.csproj -- --run-once- After completion, verify outputs:
Get-ChildItem .\.artifacts\latest
Get-ChildItem .\.artifacts\versions -Recurse
Get-Content .\.artifacts\latest\psgallery-cache.manifest.jsonExpected result:
- A ZIP artifact at
latest/psgallery-cache.zip - A manifest at
latest/psgallery-cache.manifest.json - A working SQLite file at
.artifacts\psgallery-cache.sqlite - A versioned ZIP artifact under
versions/<generated>-<hash>/
Use this when you want to debug timer-trigger behavior specifically.
- Install Azure Functions Core Tools v4.
- Open the repo root in VS Code.
- Ensure src/LocalDependencyCache.FunctionApp/local.settings.json includes:
FUNCTIONS_WORKER_RUNTIME=dotnet-isolatedTimerSchedulewith a short interval for testing (example every minute)
- Start the host:
Set-Location .\src\LocalDependencyCache.FunctionApp
func start- In VS Code, attach to the running .NET worker process.
- Wait for the timer to fire, then step through breakpoints in:
- src/LocalDependencyCache.FunctionApp/Functions/SyncCacheTimerFunction.cs
- src/LocalDependencyCache.Core/PackageCacheSyncService.cs
Notes:
RunOnStartupisfalse, so timer execution starts on schedule.- Keep the interval short during debugging, then restore it after debugging.
If debugging or local runs fail, check these in order:
- Incorrect command syntax for one-shot mode
Use:
dotnet run --project .\src\LocalDependencyCache.FunctionApp\LocalDependencyCache.FunctionApp.csproj -- --run-onceDo not use dotnet run --run-once (the argument is not forwarded correctly).
- Endpoint not reachable
- Verify
PackageCache__GalleryEndpointin src/LocalDependencyCache.FunctionApp/local.settings.json. - If you use a test feed endpoint, confirm it is reachable from your machine.
- No artifacts generated
- Confirm
PackageCache__StorageModeisFileSystemfor local runs. - Confirm
PackageCache__OutputDirectorypoints to a writable path.
- Timer does not fire while host is running
- Set
TimerScheduleto a short interval. - Restart
func startafter changing local settings.
- Build/runtime mismatch
- Run
dotnet test .\LocalDependencyCache.slnxfirst. - If tests pass but host fails, review host startup logs in terminal output.
To test Blob publishing instead of filesystem output, update local settings:
- Set
PackageCache__StorageModetoBlob - Set either:
PackageCache__BlobConnectionStringandPackageCache__BlobContainerName, orPackageCache__BlobContainerUrlfor managed identity
- Set
PackageCache__BlobBaseUrlto the public base URL you expect PSResourceGet to use (in Azure, the Front Door endpoint; see Deployment)
The manifest will then point to the published versioned SQLite file under that base URL.
Infrastructure is defined in Bicep under infra/. Production deployments run through Ev2 from the
OneBranch pipeline .pipelines/LocalDependencyCache-AzureFunction.yml.
infra/main.bicep can still be deployed directly (az deployment sub create) for development environments.
infra/main.bicep (subscription scope) creates a resource group, and infra/resources.bicep creates everything in it:
| Resource | Purpose |
|---|---|
| Function App on a Flex Consumption plan (.NET 8 isolated, system-assigned identity) | Runs SyncCacheTimerFunction |
| Function storage account (private, no shared keys) | Functions host state, timer locks, and the deployment package |
Cache storage account, cache container (anonymous blob read, no listing, no shared keys) |
Published artifacts and the sync lock |
Azure Front Door Standard profile, endpoint, origin, and /cache/* route |
Dedicated CDN in front of the cache container (separate from the Gallery CDN) |
| Log Analytics workspace and Application Insights (Entra ID auth only) | Logs and telemetry |
| Role assignments for the Function identity | Blob Data Owner + Queue/Table Data Contributor on function storage; Blob Data Contributor on cache storage; Monitoring Metrics Publisher on Application Insights |
ldcache-deploy user-assigned managed identity |
Used by the Ev2 shell extension to zip-deploy code; Website Contributor on the Function App only |
The Function App's settings are generated by the template: Blob mode, BlobContainerUrl with
managed identity, BlobBaseUrl set to the Front Door endpoint (or publicBaseUrl for a custom domain),
TopPackageCount, and /tmp/localdependencycache as the working directory because the deployed
package is read-only.
Clients read https://<front-door-endpoint>/cache/latest/psgallery-cache.manifest.json (the
manifestUrl deployment output) and download the versioned artifactUrl it contains.
Template parameters are set in infra/main.bicepparam for direct deployments and in
ev2/ServiceGroupRoot/Parameters/LocalDependencyCache.Parameters.json
for Ev2: location, namePrefix, timerSchedule (hourly by default), galleryEndpoint,
topPackageCount, retainVersions, instanceMemoryMB, and publicBaseUrl.
The pipeline's build stage publishes the Function App and assembles EV2Specs/ServiceGroupRoot into the
drop_build_main artifact; the Prod_Release stage downloads it to $(Pipeline.Workspace) and runs
ExpressV2Internal@1 with RolloutSpec-Prod.json, which:
- DeployInfrastructure: deploys LocalDependencyCache.Template.json
(compiled from
infra/resources.bicep) to therg-localdependencycacheresource group. - DeployFunctionCode: runs deploy-function-code.sh in an
Ev2 shell extension as the
ldcache-deployidentity. It downloadsBuild/functionapp.zip, finds the Function App by itsapplicationtag, runsaz functionapp deployment source config-zip, and waits forSyncCacheTimerFunctionto register.
After changing infra/resources.bicep, regenerate the Ev2 template; the CI pipeline fails if it is stale:
az bicep build --file infra/resources.bicep --outfile ev2/ServiceGroupRoot/Templates/LocalDependencyCache.Template.jsonThe organization requires production pipelines to extend an official OneBranch template; both pipelines
in .pipelines/ do.
- Onboard the service to Ev2, then create a Library variable group named
LocalDependencyCache-Ev2(Pipelines > Library) withEv2ServiceTreeId(Service Tree ID) andEv2SubscriptionId(the Ev2-registered target subscription; mark it secret), and authorize the pipeline to use it. ServiceModel.json keeps__SERVICE_TREE_ID__/__SUBSCRIPTION_ID__placeholders so the IDs stay out of this public repository; the build substitutes them into the artifact's copy and fails if either variable is missing or not a GUID. Ev2's deployment identity needs Owner (or Contributor plus User Access Administrator) on that subscription because the template creates role assignments. - Create a pipeline from
.pipelines/LocalDependencyCache-AzureFunction.yml. - Create a pipeline from
.ci/ci.ymlfor CI. Its Compliance stage needs a GitHub service connection namedComplianceGHRepowith access toPowerShell/compliance. This pipeline does not extend a OneBranch template, so it must run in an organization that allows non-governed pipelines.
| Pipeline | Purpose |
|---|---|
| .ci/ci.yml | CI on every PR to main and batched pushes to main |
| .pipelines/LocalDependencyCache.yml | Signed build and release of the LocalDependencyCache.Query NuGet package (manual) |
| .pipelines/LocalDependencyCache-AzureFunction.yml | Build and Ev2 deployment of the Azure Function (manual) |
The CI pipeline is built from two job templates in .ci:
| Template | Job |
|---|---|
| build.yml | Publishes and zips the Function App, packs LocalDependencyCache.Query, validates and lints the Bicep, checks the Ev2 ARM template is current, and publishes the functionapp, infra, and nupkg artifacts |
| test.yml | Restores, builds, and tests in Release with Azurite running; publishes test results; fails if any test was skipped (so the Blob tests cannot silently skip); optionally runs --run-once against the live Gallery and verifies the manifest, the artifact's SHA-256, and the SQLite file inside it |
CI pipeline stages:
- Build:
build.yml. - Compliance: the shared
ci-compliance.ymltemplate fromPowerShell/compliance, over thenupkgandfunctionappartifacts. - Test:
test.ymlon Windows, Ubuntu (with the live Gallery smoke test, since Azure runs Linux), and macOS.
.ci/test.yml parameters: jobName, imageName, displayName, buildConfiguration, dotnetRuntimeVersion,
runBlobTests (default true), and runGallerySmokeTest (default false).
The first timer run publishes a complete cache; there is no seeding phase. Later runs publish only when the top packages, their versions, or their dependencies change.
Front Door Standard has a monthly base fee in addition to data transfer; see Azure pricing.
The current implementation has been validated with:
dotnet test .\LocalDependencyCache.slnx
dotnet run --project .\src\LocalDependencyCache.FunctionApp\LocalDependencyCache.FunctionApp.csproj -- --run-onceThe first command verifies the parser and local artifact pipeline. The second command exercises the real host configuration and generates a local SQLite artifact and manifest.