phpmainthread_test.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. package frankenphp
  2. import (
  3. "io"
  4. "math/rand/v2"
  5. "net/http/httptest"
  6. "path/filepath"
  7. "sync"
  8. "sync/atomic"
  9. "testing"
  10. "time"
  11. "github.com/dunglas/frankenphp/internal/phpheaders"
  12. "github.com/stretchr/testify/assert"
  13. "go.uber.org/zap"
  14. )
  15. var testDataPath, _ = filepath.Abs("./testdata")
  16. func TestStartAndStopTheMainThreadWithOneInactiveThread(t *testing.T) {
  17. logger = zap.NewNop() // the logger needs to not be nil
  18. _, err := initPHPThreads(1, 1, nil) // boot 1 thread
  19. assert.NoError(t, err)
  20. assert.Len(t, phpThreads, 1)
  21. assert.Equal(t, 0, phpThreads[0].threadIndex)
  22. assert.True(t, phpThreads[0].state.is(stateInactive))
  23. drainPHPThreads()
  24. assert.Nil(t, phpThreads)
  25. }
  26. func TestTransitionRegularThreadToWorkerThread(t *testing.T) {
  27. logger = zap.NewNop()
  28. _, err := initPHPThreads(1, 1, nil)
  29. assert.NoError(t, err)
  30. // transition to regular thread
  31. convertToRegularThread(phpThreads[0])
  32. assert.IsType(t, &regularThread{}, phpThreads[0].handler)
  33. // transition to worker thread
  34. worker := getDummyWorker("transition-worker-1.php")
  35. convertToWorkerThread(phpThreads[0], worker)
  36. assert.IsType(t, &workerThread{}, phpThreads[0].handler)
  37. assert.Len(t, worker.threads, 1)
  38. // transition back to inactive thread
  39. convertToInactiveThread(phpThreads[0])
  40. assert.IsType(t, &inactiveThread{}, phpThreads[0].handler)
  41. assert.Len(t, worker.threads, 0)
  42. drainPHPThreads()
  43. assert.Nil(t, phpThreads)
  44. }
  45. func TestTransitionAThreadBetween2DifferentWorkers(t *testing.T) {
  46. logger = zap.NewNop()
  47. _, err := initPHPThreads(1, 1, nil)
  48. assert.NoError(t, err)
  49. firstWorker := getDummyWorker("transition-worker-1.php")
  50. secondWorker := getDummyWorker("transition-worker-2.php")
  51. // convert to first worker thread
  52. convertToWorkerThread(phpThreads[0], firstWorker)
  53. firstHandler := phpThreads[0].handler.(*workerThread)
  54. assert.Same(t, firstWorker, firstHandler.worker)
  55. assert.Len(t, firstWorker.threads, 1)
  56. assert.Len(t, secondWorker.threads, 0)
  57. // convert to second worker thread
  58. convertToWorkerThread(phpThreads[0], secondWorker)
  59. secondHandler := phpThreads[0].handler.(*workerThread)
  60. assert.Same(t, secondWorker, secondHandler.worker)
  61. assert.Len(t, firstWorker.threads, 0)
  62. assert.Len(t, secondWorker.threads, 1)
  63. drainPHPThreads()
  64. assert.Nil(t, phpThreads)
  65. }
  66. // try all possible handler transitions
  67. // takes around 200ms and is supposed to force race conditions
  68. func TestTransitionThreadsWhileDoingRequests(t *testing.T) {
  69. numThreads := 10
  70. numRequestsPerThread := 100
  71. isDone := atomic.Bool{}
  72. wg := sync.WaitGroup{}
  73. worker1Path := testDataPath + "/transition-worker-1.php"
  74. worker2Path := testDataPath + "/transition-worker-2.php"
  75. assert.NoError(t, Init(
  76. WithNumThreads(numThreads),
  77. WithWorkers(worker1Path, 1, map[string]string{}, []string{}),
  78. WithWorkers(worker2Path, 1, map[string]string{}, []string{}),
  79. WithLogger(zap.NewNop()),
  80. ))
  81. // try all possible permutations of transition, transition every ms
  82. transitions := allPossibleTransitions(worker1Path, worker2Path)
  83. for i := 0; i < numThreads; i++ {
  84. go func(thread *phpThread, start int) {
  85. for {
  86. for j := start; j < len(transitions); j++ {
  87. if isDone.Load() {
  88. return
  89. }
  90. transitions[j](thread)
  91. time.Sleep(time.Millisecond)
  92. }
  93. start = 0
  94. }
  95. }(phpThreads[i], i)
  96. }
  97. // randomly do requests to the 3 endpoints
  98. wg.Add(numThreads)
  99. for i := 0; i < numThreads; i++ {
  100. go func(i int) {
  101. for j := 0; j < numRequestsPerThread; j++ {
  102. switch rand.IntN(3) {
  103. case 0:
  104. assertRequestBody(t, "http://localhost/transition-worker-1.php", "Hello from worker 1")
  105. case 1:
  106. assertRequestBody(t, "http://localhost/transition-worker-2.php", "Hello from worker 2")
  107. case 2:
  108. assertRequestBody(t, "http://localhost/transition-regular.php", "Hello from regular thread")
  109. }
  110. }
  111. wg.Done()
  112. }(i)
  113. }
  114. // we are finished as soon as all 1000 requests are done
  115. wg.Wait()
  116. isDone.Store(true)
  117. Shutdown()
  118. }
  119. // Note: this test is here since it would break compilation when put into the phpheaders package
  120. func TestAllCommonHeadersAreCorrect(t *testing.T) {
  121. fakeRequest := httptest.NewRequest("GET", "http://localhost", nil)
  122. for header, phpHeader := range phpheaders.CommonRequestHeaders {
  123. // verify that common and uncommon headers return the same result
  124. expectedPHPHeader := phpheaders.GetUnCommonHeader(header)
  125. assert.Equal(t, phpHeader+"\x00", expectedPHPHeader, "header is not well formed: "+phpHeader)
  126. // net/http will capitalize lowercase headers, verify that headers are capitalized
  127. fakeRequest.Header.Add(header, "foo")
  128. _, ok := fakeRequest.Header[header]
  129. assert.True(t, ok, "header is not correctly capitalized: "+header)
  130. }
  131. }
  132. func getDummyWorker(fileName string) *worker {
  133. if workers == nil {
  134. workers = make(map[string]*worker)
  135. }
  136. worker, _ := newWorker(workerOpt{
  137. fileName: testDataPath + "/" + fileName,
  138. num: 1,
  139. })
  140. return worker
  141. }
  142. func assertRequestBody(t *testing.T, url string, expected string) {
  143. r := httptest.NewRequest("GET", url, nil)
  144. w := httptest.NewRecorder()
  145. req, err := NewRequestWithContext(r, WithRequestDocumentRoot(testDataPath, false))
  146. assert.NoError(t, err)
  147. err = ServeHTTP(w, req)
  148. assert.NoError(t, err)
  149. resp := w.Result()
  150. body, _ := io.ReadAll(resp.Body)
  151. assert.Equal(t, expected, string(body))
  152. }
  153. // create a mix of possible transitions of workers and regular threads
  154. func allPossibleTransitions(worker1Path string, worker2Path string) []func(*phpThread) {
  155. return []func(*phpThread){
  156. convertToRegularThread,
  157. func(thread *phpThread) { thread.shutdown() },
  158. func(thread *phpThread) { thread.boot() },
  159. func(thread *phpThread) { convertToWorkerThread(thread, workers[worker1Path]) },
  160. convertToInactiveThread,
  161. func(thread *phpThread) { convertToWorkerThread(thread, workers[worker2Path]) },
  162. convertToInactiveThread,
  163. }
  164. }