Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 14 additions & 18 deletions cachew.hcl
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Artifactory caching proxy strategy
# artifactory "example.jfrog.io" {
# strategy artifactory "example.jfrog.io" {
# target = "https://example.jfrog.io"
# }

Expand All @@ -13,15 +13,11 @@ opa {
policy = <<EOF
package cachew.authz
default allow := false
allow if input.method == "GET"
allow if input.method == "HEAD"
allow if startswith(input.remote_addr, "127.0.0.1:")

allow if not input.path[0] in {"api", "admin"}
EOF
}

git-clone {}

# github-app {
# app-id = "app-id-value"
# private-key-path = "private-key-path-value"
Expand All @@ -30,34 +26,34 @@ git-clone {}

metrics {}

git {
strategy git {
#bundle-interval = "24h"
snapshot-interval = "1h"
repack-interval = "1h"
}

host "https://ghcr.io" {
strategy host "https://ghcr.io" {
headers = {
"Authorization": "Bearer QQ=="
}
}

host "https://w3.org" {}
strategy host "https://w3.org" {}

github-releases {
strategy github-releases {
token = "${GITHUB_TOKEN}"
private-orgs = ["alecthomas"]
}

disk {
limit-mb = 250000
max-ttl = "8h"
}

gomod {
strategy gomod {
proxy = "https://proxy.golang.org"
}

hermit { }
strategy hermit { }

strategy proxy { }

proxy { }
cache disk {
limit-mb = 250000
max-ttl = "8h"
}
9 changes: 8 additions & 1 deletion internal/cache/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,17 @@ func Register[Config any, C Cache](r *Registry, id, description string, factory
}

// Schema returns the schema for all registered cache backends.
// Each entry is wrapped as a "cache <name> { ... }" block.
func (r *Registry) Schema() *hcl.AST {
ast := &hcl.AST{}
for _, entry := range r.registry {
ast.Entries = append(ast.Entries, entry.schema)
wrapped := &hcl.Block{
Name: "cache",
Labels: append([]string{entry.schema.Name}, entry.schema.Labels...),
Body: entry.schema.Body,
Comments: entry.schema.Comments,
}
ast.Entries = append(ast.Entries, wrapped)
}
return ast
}
Expand Down
50 changes: 39 additions & 11 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,22 @@ func Split[GlobalConfig any](ast *hcl.AST) (global, providers *hcl.AST) {
return global, providers
}

// unwrapBlock extracts the registry name from a prefixed block (e.g. "cache disk { ... }")
// and returns a copy of the block with Name set to the first label and remaining labels preserved.
func unwrapBlock(block *hcl.Block) (name string, inner *hcl.Block, err error) {
if len(block.Labels) == 0 {
return "", nil, errors.Errorf("%s: %s block requires a name label", block.Pos, block.Name)
}
inner = &hcl.Block{
Pos: block.Pos,
Name: block.Labels[0],
Labels: block.Labels[1:],
Body: block.Body,
Comments: block.Comments,
}
return block.Labels[0], inner, nil
}

// Load HCL configuration and use that to construct the cache backend, and proxy strategies.
// It returns an http.Handler that wraps mux — any loaded strategies that implement
// strategy.Interceptor are applied as middleware before ServeMux route matching, so
Expand All @@ -107,22 +123,34 @@ func Load(
{Name: "apiv1"},
}

// First pass, instantiate caches
// First pass: collect cache backends and strategy candidates from prefixed blocks.
var caches []cache.Cache
for _, node := range ast.Entries {
switch node := node.(type) {
case *hcl.Block:
c, err := cr.Create(ctx, node.Name, node, vars)
if errors.Is(err, cache.ErrNotFound) {
strategyCandidates = append(strategyCandidates, node)
continue
} else if err != nil {
return nil, errors.Errorf("%s: %w", node.Pos, err)
block, ok := node.(*hcl.Block)
if !ok {
return nil, errors.Errorf("%s: attributes are not allowed", node.Position())
}
switch block.Name {
case "cache":
name, inner, err := unwrapBlock(block)
if err != nil {
return nil, err
}
c, err := cr.Create(ctx, name, inner, vars)
if err != nil {
return nil, errors.Errorf("%s: %w", block.Pos, err)
}
caches = append(caches, c)

case *hcl.Attribute:
return nil, errors.Errorf("%s: attributes are not allowed", node.Pos)
case "strategy":
_, inner, err := unwrapBlock(block)
if err != nil {
return nil, err
}
strategyCandidates = append(strategyCandidates, inner)

default:
return nil, errors.Errorf("%s: unknown block %q (expected \"cache\" or \"strategy\")", block.Pos, block.Name)
}
}
if len(caches) == 0 {
Expand Down
42 changes: 42 additions & 0 deletions internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,48 @@ import (
"github.com/alecthomas/hcl/v2"
)

func TestUnwrapBlock(t *testing.T) {
tests := []struct {
name string
block *hcl.Block
expectedName string
expectedLabels []string
expectedErr string
}{
{
name: "SimpleBlock",
block: &hcl.Block{Name: "cache", Labels: []string{"disk"}},
expectedName: "disk",
expectedLabels: []string{},
},
{
name: "BlockWithExtraLabels",
block: &hcl.Block{Name: "strategy", Labels: []string{"host", "https://ghcr.io"}},
expectedName: "host",
expectedLabels: []string{"https://ghcr.io"},
},
{
name: "MissingLabel",
block: &hcl.Block{Name: "cache"},
expectedErr: "cache block requires a name label",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
name, inner, err := unwrapBlock(tt.block)
if tt.expectedErr != "" {
assert.Error(t, err)
assert.Contains(t, err.Error(), tt.expectedErr)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.expectedName, name)
assert.Equal(t, tt.expectedName, inner.Name)
assert.Equal(t, tt.expectedLabels, inner.Labels)
})
}
}

func TestInjectEnvars(t *testing.T) {
type Scheduler struct {
Concurrency int `hcl:"concurrency"`
Expand Down
9 changes: 8 additions & 1 deletion internal/strategy/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,17 @@ func Register[Config any, S Strategy](r *Registry, id, description string, facto
}

// Schema returns the schema for all registered strategies.
// Each entry is wrapped as a "strategy <name> { ... }" block.
func (r *Registry) Schema() *hcl.AST {
ast := &hcl.AST{}
for _, entry := range r.registry {
ast.Entries = append(ast.Entries, entry.schema)
wrapped := &hcl.Block{
Name: "strategy",
Labels: append([]string{entry.schema.Name}, entry.schema.Labels...),
Body: entry.schema.Body,
Comments: entry.schema.Comments,
}
ast.Entries = append(ast.Entries, wrapped)
}
return ast
}
Expand Down