forked from Botanical/BotanJS
Migrate old externs 7/x
This commit is contained in:
@@ -4,30 +4,37 @@ import (
|
||||
"context"
|
||||
)
|
||||
|
||||
func New(compiler Compiler, workers int, queueSize int) *Cache {
|
||||
if workers <= 0 {
|
||||
workers = 1
|
||||
func New(compiler Compiler, opt Options) *Cache {
|
||||
if opt.Workers <= 0 {
|
||||
opt.Workers = 1
|
||||
}
|
||||
if queueSize <= 0 {
|
||||
queueSize = 128
|
||||
if opt.QueueSize <= 0 {
|
||||
opt.QueueSize = 128
|
||||
}
|
||||
|
||||
c := &Cache{
|
||||
compiler: compiler,
|
||||
states: make(map[string]State),
|
||||
results: make(map[string][]byte),
|
||||
errors: make(map[string]error),
|
||||
jobs: make(chan Job, queueSize),
|
||||
compiler: compiler,
|
||||
disableCache: opt.DisableCache,
|
||||
states: make(map[string]State),
|
||||
results: make(map[string][]byte),
|
||||
errors: make(map[string]error),
|
||||
jobs: make(chan Job, opt.QueueSize),
|
||||
}
|
||||
|
||||
for i := 0; i < workers; i++ {
|
||||
go c.worker()
|
||||
if !opt.DisableCache {
|
||||
for i := 0; i < opt.Workers; i++ {
|
||||
go c.worker()
|
||||
}
|
||||
}
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *Cache) Get(hash string) (State, []byte, error) {
|
||||
if c.disableCache {
|
||||
return Missing, nil, nil
|
||||
}
|
||||
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
@@ -47,6 +54,14 @@ func (c *Cache) Get(hash string) (State, []byte, error) {
|
||||
}
|
||||
|
||||
func (c *Cache) Enqueue(job Job) State {
|
||||
if c.disableCache {
|
||||
// Pretend every request is new.
|
||||
// Caller will see Pending forever unless something else reads result,
|
||||
// so this only works if your caller does not rely on cache state.
|
||||
go c.runUncached(job)
|
||||
return Pending
|
||||
}
|
||||
|
||||
c.mu.Lock()
|
||||
|
||||
state, ok := c.states[job.Hash]
|
||||
@@ -58,12 +73,15 @@ func (c *Cache) Enqueue(job Job) State {
|
||||
c.states[job.Hash] = Pending
|
||||
c.mu.Unlock()
|
||||
|
||||
// Do not hold the lock while sending.
|
||||
c.jobs <- job
|
||||
|
||||
return Pending
|
||||
}
|
||||
|
||||
func (c *Cache) runUncached(job Job) {
|
||||
_, _ = c.compiler.Compile(context.Background(), job)
|
||||
}
|
||||
|
||||
func (c *Cache) worker() {
|
||||
for job := range c.jobs {
|
||||
c.run(job)
|
||||
|
||||
@@ -28,9 +28,17 @@ type Compiler interface {
|
||||
type Cache struct {
|
||||
compiler Compiler
|
||||
|
||||
disableCache bool
|
||||
|
||||
mu sync.Mutex
|
||||
states map[string]State
|
||||
results map[string][]byte
|
||||
errors map[string]error
|
||||
jobs chan Job
|
||||
}
|
||||
|
||||
type Options struct {
|
||||
Workers int
|
||||
QueueSize int
|
||||
DisableCache bool
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user