cdn

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: Apache-2.0 Imports: 29 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 cdn emulates Cloud CDN (SRS 5.9): the HTTP cache the load balancer puts in front of CDN-enabled backend services and backend buckets. It implements Cloud CDN's cache modes, TTL settings, cache key policies, negative caching, serve-while-stale, request coalescing, byte ranges, revalidation, signed URLs/cookies and invalidation, over a size-limited LRU store with a memory and a disk tier.

The service itself only owns the Cache and its admin endpoints; lb calls (*Cache).Serve for CDN-enabled backends (env.Lookup("cdn") and interface{ Cache() *cdn.Cache }) and (*Cache).Invalidate for urlMaps.invalidateCache.

Index

Constants

View Source
const (
	StatusHit         = "hit"
	StatusMiss        = "miss"
	StatusRevalidated = "revalidated"
	StatusUncacheable = "uncacheable"
)

Values of the {cdn_cache_status} header variable (FR-CDN-004).

View Source
const (
	CacheAllStatic   = "CACHE_ALL_STATIC"
	UseOriginHeaders = "USE_ORIGIN_HEADERS"
	ForceCacheAll    = "FORCE_CACHE_ALL"
)

Cache modes (FR-CDN-002).

View Source
const DefaultCacheSize = 1 << 30

DefaultCacheSize is the default cache size limit (FR-CDN-008).

View Source
const Name = "cdn"

Name is the service name.

View Source
const SignedCookieName = "Cloud-CDN-Cookie"

SignedCookieName is the Cloud CDN signed cookie (FR-CDN-007).

Variables

This section is empty.

Functions

func New

func New(env *emu.Env) emu.Service

New returns the service. The cache exists from construction so lb can obtain it before cdn starts; its disk tier lives under the service data directory and is rebuilt on restart in --data-dir mode.

func ParseSize

func ParseSize(v string) (int64, error)

ParseSize parses a size such as "1GiB", "512MiB", "100MB", "64k" or a plain byte count. Empty means DefaultCacheSize.

func SignCookie

func SignCookie(prefix, keyName string, key []byte, expires time.Time) string

SignCookie returns a Cloud-CDN-Cookie value for prefix.

func SignURL

func SignURL(u, keyName string, key []byte, expires time.Time) string

SignURL signs u (which must not already carry signing params) with a Cloud CDN key, like `gcloud compute sign-url`. Exported for tests and tooling.

func SignURLPrefix

func SignURLPrefix(prefix, keyName string, key []byte, expires time.Time) string

SignURLPrefix returns the query string granting access to every URL starting with prefix.

Types

type Backend

type Backend struct {
	// ID is the backend service or backend bucket selfLink; it namespaces
	// the cache and is the unit of invalidation.
	ID string
	// Kind is "backendService" or "backendBucket".
	Kind string
	// ServicePolicy or BucketPolicy is the resource's cdnPolicy.
	ServicePolicy *compute.BackendServiceCdnPolicy
	BucketPolicy  *compute.BackendBucketCdnPolicy
	// CompressionMode is the resource's compressionMode
	// ("AUTOMATIC" enables dynamic gzip compression).
	CompressionMode string
	// SignedURLKeys maps signed URL key names to their raw 16-byte
	// values (FR-CDN-007). Empty means no signature validation.
	SignedURLKeys map[string][]byte
	// SignedURLCacheMaxAgeSec overrides cdnPolicy.signedUrlCacheMaxAgeSec
	// when non-zero (default 3600).
	SignedURLCacheMaxAgeSec int64
}

Backend describes the CDN-enabled backend service or backend bucket a request is served by. lb builds it from the compute resource.

type BackendStats added in v0.4.0

type BackendStats struct {
	// Backend is the backend service or bucket's resource path.
	Backend     string `json:"backend"`
	Entries     int    `json:"entries"`
	Bytes       int64  `json:"bytes"`
	Hits        int64  `json:"hits"`
	Misses      int64  `json:"misses"`
	Revalidated int64  `json:"revalidated"`
	Uncacheable int64  `json:"uncacheable"`
}

BackendStats is one backend's cache usage and traffic.

type Cache

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

Cache is the Cloud CDN HTTP cache shared by every CDN-enabled backend.

func NewCache

func NewCache(o Options) (*Cache, error)

NewCache returns a cache; with a Dir it rebuilds its index from disk.

func (*Cache) BackendStats added in v0.4.0

func (c *Cache) BackendStats(project string) []BackendStats

BackendStats reports each backend with cached entries or traffic, in project ("" for all), sorted by backend.

func (*Cache) Entries added in v0.4.0

func (c *Cache) Entries(backend string, limit int) ([]EntryInfo, bool)

Entries lists up to limit (0 = all) of a backend's cached responses, by host and path, and whether more were left out.

func (*Cache) Invalidate

func (c *Cache) Invalidate(backendIDs []string, host, path string, cacheTags []string)

Invalidate removes the entries of the given backends (all backends when empty) whose host matches host ("" = any) and whose path matches path: exact, or a prefix when path ends in "/*" ("" = any). With cacheTags, only entries carrying one of the tags (Cache-Tag response header) match. It is effective before it returns (FR-CDN-005).

func (*Cache) Limit

func (c *Cache) Limit() int64

Limit returns the size limit in bytes.

func (*Cache) Purge

func (c *Cache) Purge()

Purge removes every cached object (FR-CDN-008) and returns the count.

func (*Cache) Serve

func (c *Cache) Serve(w http.ResponseWriter, r *http.Request, b Backend, origin http.Handler) string

Serve answers r from cache or via origin (the LB's backend handler) per Cloud CDN rules and returns the {cdn_cache_status} value: "hit", "miss", "revalidated" or "uncacheable" (FR-CDN-001..007). It counts the value for the backend's hit ratio.

func (*Cache) Stats

func (c *Cache) Stats() (entries int, bytes int64)

Stats reports the number of entries and the bytes they use.

func (*Cache) Wait

func (c *Cache) Wait()

Wait blocks until background revalidations finish (tests, shutdown).

type Clock

type Clock interface{ Now() time.Time }

Clock is the time source of a Cache.

type EntryInfo added in v0.4.0

type EntryInfo struct {
	Host        string    `json:"host"`
	Path        string    `json:"path"`
	CacheKey    string    `json:"cacheKey"`
	Status      int       `json:"status"`
	Bytes       int64     `json:"bytes"`
	ContentType string    `json:"contentType,omitempty"`
	Stored      time.Time `json:"stored"`
	Age         int64     `json:"age"`
	TTL         int64     `json:"ttl"`
	Vary        []string  `json:"vary,omitempty"`
	Tags        []string  `json:"tags,omitempty"`
	// Tier is "memory" when the body is held in memory, else "disk".
	Tier string `json:"tier"`
}

EntryInfo is one cached response, as the console lists it.

type Options

type Options struct {
	// Dir is the disk tier directory; "" keeps everything in memory.
	Dir string
	// MaxBytes is the size limit (default DefaultCacheSize).
	MaxBytes int64
	// Clock defaults to the wall clock.
	Clock Clock
}

Options configure a Cache.

type Service

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

Service is the Cloud CDN service module.

func (*Service) Cache

func (s *Service) Cache() *Cache

Cache returns the shared CDN cache (the CDN ⇄ LB contract).

func (*Service) Name

func (s *Service) Name() string

Name implements emu.Service.

func (*Service) Ready

func (s *Service) Ready() error

Ready implements emu.Service.

func (*Service) Register

func (s *Service) Register(r emu.Router) error

Register mounts the admin endpoints:

POST /_emu/v1/cdn/purge    clears the cache (`gcpemu cdn purge`)
GET  /_emu/v1/cdn          reports entries, bytes used and the limit, and each backend's
GET  /_emu/v1/cdn/entries  lists a backend's cached entries

Purging keeps the backends' hit and miss totals; Reset clears them.

func (*Service) Reset

func (s *Service) Reset(ctx context.Context) error

Reset clears the cache and the backends' totals on `gcpemu reset`.

func (*Service) Start

func (s *Service) Start(ctx context.Context) error

Start implements emu.Service.

func (*Service) Stop

func (s *Service) Stop(ctx context.Context) error

Stop waits for background revalidations.

Jump to

Keyboard shortcuts

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