siteassets

package
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 14 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package siteassets resolves per-site MinIO/S3 assets to their content-addressed counterparts via a manifest emitted by storage-sync.

Why a manifest

The platform serves per-site logos, demo fixtures, and customer uploads from MinIO at `cloud/assets/<organization_id>/<site_id>/<key>`. Without versioning, replacing `logo.png` under the same key keeps browsers and CDNs serving the old bytes until heuristic TTLs expire. The fix is the standard content-addressable pattern: upload the file as `logo-<hash>.png` and let the URL change when the content changes. Templates keep referring to the logical name (`logo.png`) and a sidecar manifest carries the logical → hashed mapping so the runtime can rewrite at render time.

Flow

storage-sync sync --apply:
    1. SHA-256 of each file → 8 hex chars.
    2. PUT as <basename>-<hash>.<ext> with
       Cache-Control: public, max-age=31536000, immutable.
    3. Write `_manifest.json` per <orgID>/<siteID>/ dir.

service render path:
    1. ManifestCache.Get(orgID, siteID) loads _manifest.json
       lazily, TTL-cached in memory.
    2. cdnURL template helper rewrites
       "cloud/assets/<org>/<site>/logo.png" →
       "cloud/assets/<org>/<site>/logo-abc12345.png" via the
       manifest, then composes the final URL via siteurl.BuildCDNURL.

Decoupling from a storage backend

The Loader function in ManifestCache is the only seam between this package and the actual storage. A service using minio-go directly supplies a closure; a future consumer of `service-storage` supplies a different one; tests inject in-memory fixtures. The package itself never imports a storage SDK.

Graceful degradation

Every public helper falls through to the unhashed name when the manifest is absent, the asset isn't in it, or the loader errors. This keeps services safe to wire on day one, before storage-sync has ever run for that site, and survives a transiently broken bucket.

Index

Constants

View Source
const ManifestBasename = "_manifest.json"

ManifestBasename is the conventional filename for the per-site asset manifest emitted by storage-sync and consumed by every Loader. Exported so the writer (storage-sync) and the readers (Loaders) reference one constant — drift here means readers fetch a path the writer never produced.

View Source
const ManifestCurrentSchemaVersion = 1

ManifestCurrentSchemaVersion is the wire-shape version writers stamp into every new manifest. Bump on any breaking field change and add the older shape to an UpgradeFromV path when that ships — same per-document `_v` convention as Mongo models.

Variables

This section is empty.

Functions

func FuncMap

func FuncMap(cache *ManifestCache) template.FuncMap

FuncMap returns the template helpers a service merges into its render funcmap to gain manifest-aware asset resolution. Two helpers, two call shapes:

  • cdnURL replaces siteurl.BuildCDNURL: same signature, paths that match the canonical per-site convention get rewritten to their hashed names; everything else passes through.
  • siteAsset is the explicit form for multi-tenant render contexts (service-sites, service-console) where the template has the tenant in scope: `{{ siteAsset .Site.OrgID .Site.ID "logo.png" }}`.

Both fall back gracefully — missing manifest, missing asset, nil cache, paths outside the convention — by returning the unhashed URL. Safe to wire on day one, before storage-sync has run.

func MakeCDNURL

func MakeCDNURL(cache *ManifestCache) func(string) string

MakeCDNURL returns a drop-in replacement for siteurl.BuildCDNURL that rewrites bucket-relative paths matching assetPathPattern to their content-addressed counterparts before composing the final CDN URL.

Behaviour:

  • Matching path + manifest has the asset → emit hashed name.
  • Matching path + manifest absent or missing asset → emit unhashed name (graceful fallback).
  • Non-matching path (absolute URL, ExtraStatic mount, …) → delegates straight to siteurl.BuildCDNURL.

Templates always end up with a working URL, even before storage-sync has ever run for that site.

Types

type Loader

type Loader func(ctx context.Context, orgID, siteID string) ([]byte, error)

Loader fetches the raw JSON bytes of a manifest for one (orgID, siteID) pair. Injected into ManifestCache so this package stays decoupled from any specific storage backend (minio-go directly, a future service-storage HTTP client, an in-memory fixture).

Contract:

  • On success: returns the manifest bytes and a nil error.
  • When no manifest exists for the pair (storage-sync hasn't run yet, or the site has no assets): returns (nil, nil) — NOT an error. This is the normal "absent" state; callers fall back to logical names.
  • On real failures (network, auth, parse upstream): returns (nil, err).

type Manifest

type Manifest struct {
	SchemaV int               `json:"_v"`
	Assets  map[string]string `json:"assets"`
}

Manifest maps logical asset names (e.g. "logo.png") to their content-addressed hashed counterparts (e.g. "logo-abc12345.png") within one `<organization_id>/<site_id>/` scope. storage-sync emits one Manifest per site directory; ManifestCache reads them on demand to rewrite template URLs to their hashed form.

The map is intentionally flat — subdirectories under a site (e.g. `img/hero.jpg`) are encoded as forward-slash keys, so a single hash lookup serves any depth. Keeping logical→hashed in one JSON keeps the rewrite a memory map lookup instead of a per-key HEAD round trip.

func ParseManifest

func ParseManifest(raw []byte) (*Manifest, error)

ParseManifest decodes raw JSON bytes into a Manifest. Empty input returns (nil, nil) so callers can treat "manifest absent" and "manifest is the empty object" as equivalently "no rewriting possible" without surfacing a parse error to the template hot path.

func (*Manifest) Resolve

func (m *Manifest) Resolve(logical string) string

Resolve returns the hashed name for `logical` if the manifest carries it, or "" otherwise. A nil receiver is acceptable and also returns "" — callers pass a ManifestCache.Get result directly without nil-checking and rely on the "" sentinel to fall back to the logical name.

type ManifestCache

type ManifestCache struct {
	// contains filtered or unexported fields
}

ManifestCache is a goroutine-safe in-memory cache of Manifests keyed by (orgID, siteID). Misses trigger Loader; subsequent hits within `ttl` serve from memory.

TTL semantics:

  • ttl > 0: entries expire after `ttl` and are re-fetched on the next access.
  • ttl == 0: entries never expire automatically — refresh only via Invalidate. Useful in services that subscribe to a NATS "manifest updated" message and invalidate on demand.

func NewAssetsCache

func NewAssetsCache(ttl time.Duration) *ManifestCache

NewAssetsCache builds the ManifestCache a public asset consumer wires. It resolves the per-site manifest over anonymous HTTP from the PUBLIC endpoint (see publicAssetsEndpoint) — never the private/credentialed MinIO endpoint, which in prod is usually cluster-internal and unreachable for a public read. Nil (and a log line) when nothing resolves a base/bucket, so the caller can wire it unconditionally and degrade to logical names.

func NewHTTPManifestCache

func NewHTTPManifestCache(endpoint, bucket string, useSSL bool, ttl time.Duration) *ManifestCache

NewHTTPManifestCache builds a ManifestCache backed by an anonymous HTTP loader against a public S3/MinIO endpoint. This is the drop-in a service wires when it only needs to resolve hashed asset URLs (no credentials, read-only, public objects).

Returns nil when endpoint or bucket is empty so the caller can wire it unconditionally and let the nil-safe ManifestCache degrade to logical names (a dev running without an asset host still gets working, just-not-immutably-cached, URLs).

func NewManifestCache

func NewManifestCache(loader Loader, ttl time.Duration) *ManifestCache

NewManifestCache returns a fresh cache. A nil loader is allowed and produces a cache whose Get always returns (nil, nil) — handy as a no-op binding when the service has no asset host configured yet, without forcing every call site to nil-check.

func (*ManifestCache) Get

func (c *ManifestCache) Get(ctx context.Context, orgID, siteID string) (*Manifest, error)

Get returns the Manifest for (orgID, siteID), loading via the Loader on miss or after TTL expiry. A nil Manifest with a nil error means "no manifest exists for this pair" — callers treat it as "fall back to logical names".

A nil receiver also returns (nil, nil) so a service that hasn't wired a cache yet can still pass `nil` through every helper without nil-guards at each call site.

func (*ManifestCache) Invalidate

func (c *ManifestCache) Invalidate(orgID, siteID string)

Invalidate drops the cached entry for (orgID, siteID), forcing the next Get to re-fetch via the Loader. No-op when the key isn't cached, or on a nil receiver. Safe to call concurrently with Get.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL