Skip to content

Commit 0b22d51

Browse files
committed
refactor to using name instead of moduleID
1 parent bc48bdd commit 0b22d51

12 files changed

Lines changed: 106 additions & 113 deletions

caddy/caddy.go

Lines changed: 35 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,10 @@
44
package caddy
55

66
import (
7-
"crypto/sha256"
8-
"encoding/binary"
97
"encoding/json"
108
"errors"
119
"fmt"
10+
"github.com/davecgh/go-spew/spew"
1211
"net/http"
1312
"path/filepath"
1413
"strconv"
@@ -53,7 +52,7 @@ func init() {
5352
}
5453

5554
type workerConfig struct {
56-
// Name for the worker
55+
// Name for the worker. Default: the filename for FrankenPHPApp workers, filename + environment variables for FrankenPHPModule workers.
5756
Name string `json:"name,omitempty"`
5857
// FileName sets the path to the worker script.
5958
FileName string `json:"file_name,omitempty"`
@@ -63,8 +62,6 @@ type workerConfig struct {
6362
Env map[string]string `json:"env,omitempty"`
6463
// Directories to watch for file changes
6564
Watch []string `json:"watch,omitempty"`
66-
// ModuleID identifies which module created this worker
67-
ModuleID uint64 `json:"module_id,omitempty"`
6865
}
6966

7067
type FrankenPHPApp struct {
@@ -119,20 +116,17 @@ func (f *FrankenPHPApp) Start() error {
119116
frankenphp.WithMaxWaitTime(f.MaxWaitTime),
120117
}
121118
// Add workers from FrankenPHPApp configuration
122-
for _, w := range f.Workers {
123-
opts = append(opts, frankenphp.WithWorkers(w.Name, repl.ReplaceKnown(w.FileName, ""), w.Num, w.Env, w.Watch, w.ModuleID))
124-
}
125-
126-
// Add workers from FrankenPHPModule configurations
127-
for _, w := range sharedState.Workers {
128-
opts = append(opts, frankenphp.WithWorkers(w.Name, repl.ReplaceKnown(w.FileName, ""), w.Num, w.Env, w.Watch, w.ModuleID))
119+
for _, w := range append(f.Workers, sharedState.Workers...) {
120+
opts = append(opts, frankenphp.WithWorkers(w.Name, repl.ReplaceKnown(w.FileName, ""), w.Num, w.Env, w.Watch))
129121
}
130122

131123
frankenphp.Shutdown()
132124
if err := frankenphp.Init(opts...); err != nil {
133125
return err
134126
}
135127

128+
caddy.Log().Warn(fmt.Sprintf("FrankenPHPApp started with workers: %s", spew.Sdump(append(f.Workers, sharedState.Workers...))))
129+
136130
return nil
137131
}
138132

@@ -360,8 +354,6 @@ type FrankenPHPModule struct {
360354
ResolveRootSymlink *bool `json:"resolve_root_symlink,omitempty"`
361355
// Env sets an extra environment variable to the given value. Can be specified more than once for multiple environment variables.
362356
Env map[string]string `json:"env,omitempty"`
363-
// ModuleID is the module ID that created this request.
364-
ModuleID uint64 `json:"-"`
365357
// Workers configures the worker scripts to start.
366358
Workers []workerConfig `json:"workers,omitempty"`
367359

@@ -436,17 +428,6 @@ func (f *FrankenPHPModule) Provision(ctx caddy.Context) error {
436428
}
437429

438430
if len(f.Workers) > 0 {
439-
envString := ""
440-
for k, v := range f.Env {
441-
envString += k + "=" + v + ","
442-
}
443-
data := []byte(f.Root + envString)
444-
hash := sha256.Sum256(data)
445-
f.ModuleID = binary.LittleEndian.Uint64(hash[:8])
446-
447-
for i := range f.Workers {
448-
f.Workers[i].ModuleID = f.ModuleID
449-
}
450431
sharedState.Workers = append(sharedState.Workers, f.Workers...)
451432
}
452433

@@ -479,13 +460,20 @@ func (f *FrankenPHPModule) ServeHTTP(w http.ResponseWriter, r *http.Request, _ c
479460
}
480461
}
481462

463+
workerNames := make([]string, len(f.Workers))
464+
for i, w := range f.Workers {
465+
workerNames[i] = w.Name
466+
}
467+
468+
caddy.Log().Info(fmt.Sprintf("ServeHTTP module has workers: %s", spew.Sdump(f.Workers)))
469+
482470
fr, err := frankenphp.NewRequestWithContext(
483471
r,
484472
documentRootOption,
485473
frankenphp.WithRequestSplitPath(f.SplitPath),
486474
frankenphp.WithRequestPreparedEnv(env),
487475
frankenphp.WithOriginalRequest(&origReq),
488-
frankenphp.WithModuleID(f.ModuleID),
476+
frankenphp.WithWorkerNames(workerNames),
489477
)
490478

491479
if err != nil {
@@ -637,11 +625,32 @@ func (f *FrankenPHPModule) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
637625
}
638626
}
639627

628+
if wc.Name == "" {
629+
name, _ := fastabs.FastAbs(wc.FileName)
630+
if name == "" {
631+
name = wc.FileName
632+
}
633+
wc.Name = name
634+
635+
if len(wc.Env) > 0 {
636+
envString := ""
637+
for k, v := range wc.Env {
638+
envString += k + "=" + v + ","
639+
}
640+
wc.Name += "#" + envString
641+
}
642+
}
643+
if !strings.HasPrefix(wc.Name, "m#") {
644+
wc.Name = "m#" + wc.Name
645+
}
646+
640647
f.Workers = append(f.Workers, wc)
641648
}
642649
}
643650
}
644651

652+
caddy.Log().Warn(fmt.Sprintf("FrankenPHPModule UnmarshalCaddyfile with workers: %s", spew.Sdump(f.Workers)))
653+
645654
return nil
646655
}
647656

caddy/caddy_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ func TestGlobalAndLocalWorker(t *testing.T) {
161161
}
162162
`, "caddyfile")
163163

164-
for i := 0; i < 100; i++ {
164+
for i := 0; i < 2; i++ {
165165
wg.Add(1)
166166

167167
go func(i int) {

context.go

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ type frankenPHPContext struct {
2323
pathInfo string
2424
scriptName string
2525
scriptFilename string
26+
workerNames []string
2627

2728
// Whether the request is already closed by us
2829
isDone bool
@@ -31,9 +32,6 @@ type frankenPHPContext struct {
3132

3233
done chan interface{}
3334
startedAt time.Time
34-
35-
// The module ID that created this request
36-
moduleID uint64
3735
}
3836

3937
// fromContext extracts the frankenPHPContext from a context.
@@ -42,8 +40,7 @@ func fromContext(ctx context.Context) (fctx *frankenPHPContext, ok bool) {
4240
return
4341
}
4442

45-
// NewRequestWithContext creates a new FrankenPHP request context.
46-
func NewRequestWithContext(r *http.Request, opts ...RequestOption) (*http.Request, error) {
43+
func newFrankenPHPContext(r *http.Request, opts ...RequestOption) (*frankenPHPContext, error) {
4744
fc := &frankenPHPContext{
4845
done: make(chan interface{}),
4946
startedAt: time.Now(),
@@ -94,7 +91,15 @@ func NewRequestWithContext(r *http.Request, opts ...RequestOption) (*http.Reques
9491

9592
// SCRIPT_FILENAME is the absolute path of SCRIPT_NAME
9693
fc.scriptFilename = sanitizedPathJoin(fc.documentRoot, fc.scriptName)
94+
return fc, nil
95+
}
9796

97+
// NewRequestWithContext creates a new FrankenPHP request context.
98+
func NewRequestWithContext(r *http.Request, opts ...RequestOption) (*http.Request, error) {
99+
fc, err2 := newFrankenPHPContext(r, opts...)
100+
if err2 != nil {
101+
return nil, err2
102+
}
98103
c := context.WithValue(r.Context(), contextKey, fc)
99104

100105
return r.WithContext(c), nil

frankenphp.go

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import (
3232
"bytes"
3333
"errors"
3434
"fmt"
35+
"github.com/davecgh/go-spew/spew"
3536
"io"
3637
"net/http"
3738
"os"
@@ -292,6 +293,8 @@ func Init(options ...Option) error {
292293
return err
293294
}
294295

296+
logger.Warn(fmt.Sprintf("FrankenPHP initialised workers: %s", spew.Sdump(opt.workers)))
297+
295298
initAutoScaling(mainThread)
296299

297300
if c := logger.Check(zapcore.InfoLevel, "FrankenPHP started 🐘"); c != nil {
@@ -404,14 +407,20 @@ func ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) error
404407
return nil
405408
}
406409

407-
// Detect if a worker is available to handle this request
408-
if worker := getWorkerForContext(fc); worker != nil {
409-
worker.handleRequest(fc)
410-
} else {
411-
// If no worker was available, send the request to non-worker threads
412-
handleRequestWithRegularPHPThreads(fc)
410+
workerNames := append(fc.workerNames, "")
411+
fc.logger.Warn(fmt.Sprintf("ServeHTTP Worker Names: %s", spew.Sdump(workerNames)))
412+
for _, workerName := range workerNames {
413+
// Detect if a worker is available to handle this request
414+
workername := workerName + fc.scriptFilename
415+
if worker := getWorkerForName(workername); worker != nil {
416+
fc.logger.Info(fmt.Sprintf("Found worker: %s", workername))
417+
worker.handleRequest(fc)
418+
return nil
419+
}
413420
}
414421

422+
// If no worker was available, send the request to non-worker threads
423+
handleRequestWithRegularPHPThreads(fc)
415424
return nil
416425
}
417426

frankenphp_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ func runTest(t *testing.T, test func(func(http.ResponseWriter, *http.Request), *
6565

6666
initOpts := []frankenphp.Option{frankenphp.WithLogger(opts.logger)}
6767
if opts.workerScript != "" {
68-
initOpts = append(initOpts, frankenphp.WithWorkers("workerName", testDataDir+opts.workerScript, opts.nbWorkers, opts.env, opts.watch, 0))
68+
initOpts = append(initOpts, frankenphp.WithWorkers("workerName", testDataDir+opts.workerScript, opts.nbWorkers, opts.env, opts.watch))
6969
}
7070
initOpts = append(initOpts, opts.initOpts...)
7171
if opts.phpIni != nil {

options.go

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@ type workerOpt struct {
2828
num int
2929
env PreparedEnv
3030
watch []string
31-
moduleID uint64
3231
}
3332

3433
// WithNumThreads configures the number of PHP threads to start.
@@ -56,10 +55,10 @@ func WithMetrics(m Metrics) Option {
5655
}
5756
}
5857

59-
// WithWorkers configures the PHP workers to start, moduleID is used to identify the worker for a specific domain
60-
func WithWorkers(name string, fileName string, num int, env map[string]string, watch []string, moduleID uint64) Option {
58+
// WithWorkers configures the PHP workers to start
59+
func WithWorkers(name string, fileName string, num int, env map[string]string, watch []string) Option {
6160
return func(o *opt) error {
62-
o.workers = append(o.workers, workerOpt{name, fileName, num, PrepareEnv(env), watch, moduleID})
61+
o.workers = append(o.workers, workerOpt{name, fileName, num, PrepareEnv(env), watch})
6362

6463
return nil
6564
}

phpmainthread_test.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -96,8 +96,8 @@ func TestTransitionThreadsWhileDoingRequests(t *testing.T) {
9696

9797
assert.NoError(t, Init(
9898
WithNumThreads(numThreads),
99-
WithWorkers(worker1Name, worker1Path, 1, map[string]string{"ENV1": "foo"}, []string{}, 0),
100-
WithWorkers(worker2Name, worker2Path, 1, map[string]string{"ENV1": "foo"}, []string{}, 0),
99+
WithWorkers(worker1Name, worker1Path, 1, map[string]string{"ENV1": "foo"}, []string{}),
100+
WithWorkers(worker2Name, worker2Path, 1, map[string]string{"ENV1": "foo"}, []string{}),
101101
WithLogger(zap.NewNop()),
102102
))
103103

@@ -182,7 +182,7 @@ func TestFinishBootingAWorkerScript(t *testing.T) {
182182

183183
func getDummyWorker(fileName string) *worker {
184184
if workers == nil {
185-
workers = make(map[string][]*worker)
185+
workers = make(map[string]*worker)
186186
}
187187
worker, _ := newWorker(workerOpt{
188188
fileName: testDataPath + "/" + fileName,
@@ -214,9 +214,9 @@ func allPossibleTransitions(worker1Path string, worker2Path string) []func(*phpT
214214
thread.boot()
215215
}
216216
},
217-
func(thread *phpThread) { convertToWorkerThread(thread, workers[worker1Path][0]) },
217+
func(thread *phpThread) { convertToWorkerThread(thread, workers[worker1Path]) },
218218
convertToInactiveThread,
219-
func(thread *phpThread) { convertToWorkerThread(thread, workers[worker2Path][0]) },
219+
func(thread *phpThread) { convertToWorkerThread(thread, workers[worker2Path]) },
220220
convertToInactiveThread,
221221
}
222222
}

request_options.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -124,10 +124,10 @@ func WithRequestLogger(logger *zap.Logger) RequestOption {
124124
}
125125
}
126126

127-
// WithModuleID sets the module ID associated with the current request
128-
func WithModuleID(moduleID uint64) RequestOption {
127+
// WithRequestLogger sets the logger associated with the current request
128+
func WithWorkerNames(names []string) RequestOption {
129129
return func(o *frankenPHPContext) error {
130-
o.moduleID = moduleID
130+
o.workerNames = names
131131

132132
return nil
133133
}

scaling.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ func startUpscalingThreads(maxScaledThreads int, scale chan *frankenPHPContext,
160160
}
161161

162162
// if the request has been stalled long enough, scale
163-
if worker := getWorkerForContext(fc); worker != nil {
163+
if worker := getWorkerForName(fc.scriptFilename); worker != nil {
164164
scaleWorkerThread(worker)
165165
} else {
166166
scaleRegularThread()

scaling_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,14 +36,14 @@ func TestScaleAWorkerThreadUpAndDown(t *testing.T) {
3636
assert.NoError(t, Init(
3737
WithNumThreads(2),
3838
WithMaxThreads(3),
39-
WithWorkers(workerName, workerPath, 1, map[string]string{}, []string{}, 0),
39+
WithWorkers(workerName, workerPath, 1, map[string]string{}, []string{}),
4040
WithLogger(zap.NewNop()),
4141
))
4242

4343
autoScaledThread := phpThreads[2]
4444

4545
// scale up
46-
scaleWorkerThread(workers[workerPath][0])
46+
scaleWorkerThread(workers[workerPath])
4747
assert.Equal(t, stateReady, autoScaledThread.state.get())
4848

4949
// on down-scale, the thread will be marked as inactive

0 commit comments

Comments
 (0)