303 lines
12 KiB
Go
303 lines
12 KiB
Go
//go:build pipeline
|
|
|
|
package studenttests_test
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/base64"
|
|
"reflect"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"golang.org/x/image/webp"
|
|
)
|
|
|
|
func pipelineS3Gate(t *testing.T, suffix string) (string, func(string) string) {
|
|
t.Helper()
|
|
proxy := "pipeline-gate-" + uuid.NewString()
|
|
workerContainer := workerCommand(t, "compose", "ps", "-a", "-q", "worker")
|
|
network := workerCommand(t, "inspect", "--format",
|
|
"{{range $name, $value := .NetworkSettings.Networks}}{{$name}}{{end}}", workerContainer)
|
|
t.Cleanup(func() { workerCommand(t, "rm", "-f", proxy) })
|
|
const proxyScript = `
|
|
import base64
|
|
import http.client
|
|
import http.server
|
|
import threading
|
|
import sys
|
|
|
|
waiting = threading.Event()
|
|
release = threading.Event()
|
|
written = threading.Event()
|
|
held_body = b''
|
|
|
|
class Proxy(http.server.BaseHTTPRequestHandler):
|
|
def log_message(self, *args):
|
|
pass
|
|
|
|
def do_GET(self):
|
|
if self.path == '/_body':
|
|
self.send_response(200)
|
|
self.end_headers()
|
|
self.wfile.write(base64.b64encode(held_body))
|
|
return
|
|
if self.path == '/_state':
|
|
data = f'{int(waiting.is_set())}:{int(written.is_set())}'.encode()
|
|
self.send_response(200)
|
|
self.end_headers()
|
|
self.wfile.write(data)
|
|
return
|
|
if self.path == '/_release':
|
|
release.set()
|
|
self.send_response(200)
|
|
self.end_headers()
|
|
return
|
|
self.forward()
|
|
|
|
def do_PUT(self):
|
|
self.forward()
|
|
|
|
def forward(self):
|
|
global held_body
|
|
body = self.rfile.read(int(self.headers.get('Content-Length', 0)))
|
|
gated = self.command == 'PUT' and self.path.split('?')[0].endswith(sys.argv[1])
|
|
if gated:
|
|
held_body = body
|
|
waiting.set()
|
|
if not release.wait(90):
|
|
self.send_error(504)
|
|
return
|
|
conn = http.client.HTTPConnection('s3', 9000, timeout=20)
|
|
try:
|
|
conn.request(self.command, self.path, body, dict(self.headers))
|
|
response = conn.getresponse()
|
|
data = response.read()
|
|
if gated and response.status == 200:
|
|
written.set()
|
|
self.send_response(response.status)
|
|
for name, value in response.getheaders():
|
|
if name.lower() not in ('connection', 'transfer-encoding', 'content-length'):
|
|
self.send_header(name, value)
|
|
self.send_header('Content-Length', str(len(data)))
|
|
self.end_headers()
|
|
self.wfile.write(data)
|
|
finally:
|
|
conn.close()
|
|
|
|
http.server.ThreadingHTTPServer(('0.0.0.0', 9000), Proxy).serve_forever()
|
|
`
|
|
workerCommand(t, "run", "-d", "--name", proxy, "--network", network,
|
|
"python:3.13.9-alpine3.22", "python", "-u", "-c", proxyScript, suffix)
|
|
control := func(path string) string {
|
|
t.Helper()
|
|
return workerCommand(t, "exec", proxy, "python", "-c",
|
|
"import urllib.request; print(urllib.request.urlopen('http://127.0.0.1:9000/"+path+"').read().decode())")
|
|
}
|
|
return proxy, control
|
|
}
|
|
|
|
func TestPipelineStaleProcessing(t *testing.T) {
|
|
user := createUser(t)
|
|
chat := createChat(t, user, user.ID)
|
|
stopService(t, "worker")
|
|
if workerQueue(t) != "0:0" {
|
|
t.Fatal("run on an idle stand with an empty attachment queue")
|
|
}
|
|
att, source := workerUpload(t, user, chat.ID)
|
|
id := att.ID.String()
|
|
where := "attachment_id='" + id + "'"
|
|
jobID := workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'")
|
|
|
|
// Hold the last v1 PUT while v2 completes, without a DB row lock.
|
|
proxy, control := pipelineS3Gate(t, "/v1/optimized")
|
|
oldWorker := "pipeline-v1-" + uuid.NewString()
|
|
t.Cleanup(func() { workerCommand(t, "rm", "-f", oldWorker) })
|
|
workerCommand(t, "compose", "run", "-d", "--no-deps", "--name", oldWorker,
|
|
"-e", "WORKER_CONCURRENCY=1", "-e", "JOB_TIMEOUT_SECONDS=120",
|
|
"-e", "S3_ENDPOINT=http://"+proxy+":9000", "worker")
|
|
workerWait(t, "v1 waiting before optimized PUT", 20*time.Second, func() bool {
|
|
return control("_state") == "1:0"
|
|
})
|
|
if workerSQL(t, "SELECT pipeline_version||':'||status||':'||attempts FROM attachments WHERE id='"+id+"'") != "1:processing:1" {
|
|
t.Fatal("v1 was not processing before upgrade")
|
|
}
|
|
|
|
workerCommand(t, "compose", "run", "--rm", "--no-deps", "worker", "-upgrade", id)
|
|
compose(t, "start", "worker")
|
|
ready := waitAttachment(t, user, att.ID, "ready", 30*time.Second)
|
|
if len(ready.Variants) != 3 ||
|
|
workerSQL(t, "SELECT pipeline_version||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:2" {
|
|
t.Fatal("v2 did not become ready while v1 was held")
|
|
}
|
|
content := make(map[string][]byte)
|
|
for _, name := range []string{"original", "thumbnail", "crop", "optimized"} {
|
|
content[name] = workerContent(t, user, att.ID, name)
|
|
}
|
|
if !bytes.Equal(content["original"], source) {
|
|
t.Fatal("v2 changed original bytes")
|
|
}
|
|
v1, err := base64.StdEncoding.DecodeString(control("_body"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, data := range [][]byte{v1, content["optimized"]} {
|
|
cfg, err := webp.DecodeConfig(bytes.NewReader(data))
|
|
if err != nil || cfg.Width != 320 || cfg.Height != 200 {
|
|
t.Fatal("expected valid optimized WebP from both versions")
|
|
}
|
|
}
|
|
if bytes.Equal(v1, content["optimized"]) {
|
|
t.Fatal("fixture must produce different v1 and v2 optimized bytes")
|
|
}
|
|
|
|
control("_release")
|
|
workerWait(t, "late v1 S3 write", 20*time.Second, func() bool {
|
|
return control("_state") == "1:1"
|
|
})
|
|
workerWait(t, "stale v1 redelivery acknowledged", 15*time.Second, func() bool {
|
|
return workerQueue(t) == "0:0"
|
|
})
|
|
after := waitAttachment(t, user, att.ID, "ready", 5*time.Second)
|
|
if !reflect.DeepEqual(ready, after) ||
|
|
workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") != jobID ||
|
|
workerSQL(t, "SELECT pipeline_version||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:2" ||
|
|
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where+" AND pipeline_version=1") != "0" ||
|
|
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where+" AND pipeline_version=2") != "3" {
|
|
t.Fatal("late v1 processing changed current metadata")
|
|
}
|
|
for name, before := range content {
|
|
if !bytes.Equal(before, workerContent(t, user, att.ID, name)) {
|
|
t.Fatalf("late v1 processing overwrote %s", name)
|
|
}
|
|
}
|
|
t.Logf("PASS attachment=%s: held v1 PUT; v2 ready; late v1 wrote S3 but could not replace v2; stale redelivery acknowledged", id)
|
|
}
|
|
|
|
func TestPipelineReorderAndDuplicate(t *testing.T) {
|
|
user := createUser(t)
|
|
chat := createChat(t, user, user.ID)
|
|
stopService(t, "worker")
|
|
if workerQueue(t) != "0:0" {
|
|
t.Fatal("run on an idle stand with an empty attachment queue")
|
|
}
|
|
// Keep v1 durable in outbox, but delay its publication until v2 is ready.
|
|
stopService(t, "rabbitmq")
|
|
att, source := workerUpload(t, user, chat.ID)
|
|
id := att.ID.String()
|
|
where := "attachment_id='" + id + "'"
|
|
jobID := workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'")
|
|
workerSQL(t, "UPDATE outbox SET available_at=now()+interval '1 hour' WHERE "+where)
|
|
if workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+" AND published_at IS NULL") != "1" {
|
|
t.Fatal("v1 was published before the reorder injection")
|
|
}
|
|
workerCommand(t, "compose", "run", "--rm", "--no-deps", "worker", "-upgrade", id)
|
|
compose(t, "start", "rabbitmq", "worker")
|
|
ready := waitAttachment(t, user, att.ID, "ready", 40*time.Second)
|
|
workerWait(t, "v2 acknowledgement", 15*time.Second, func() bool {
|
|
return workerQueue(t) == "0:0"
|
|
})
|
|
if len(ready.Variants) != 3 ||
|
|
workerSQL(t, "SELECT pipeline_version||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:1" ||
|
|
workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+" AND pipeline_version=1 AND published_at IS NULL") != "1" {
|
|
t.Fatal("v2 did not finish before v1 publication")
|
|
}
|
|
content := make(map[string][]byte)
|
|
for _, name := range []string{"original", "thumbnail", "crop", "optimized"} {
|
|
content[name] = workerContent(t, user, att.ID, name)
|
|
}
|
|
if !bytes.Equal(content["original"], source) {
|
|
t.Fatal("v2 changed original bytes")
|
|
}
|
|
|
|
for _, injection := range []struct {
|
|
name, query, version string
|
|
}{
|
|
{"reordered v1", "UPDATE outbox SET available_at=now() WHERE " + where + " AND pipeline_version=1", "1"},
|
|
{"duplicate v2", "UPDATE outbox SET published_at=NULL WHERE " + where + " AND pipeline_version=2", "2"},
|
|
} {
|
|
compose(t, "stop", "worker")
|
|
workerSQL(t, injection.query)
|
|
workerWait(t, injection.name+" published", 15*time.Second, func() bool {
|
|
return workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+
|
|
" AND pipeline_version="+injection.version+" AND published_at IS NOT NULL") == "1" &&
|
|
workerQueue(t) == "1:0"
|
|
})
|
|
compose(t, "start", "worker")
|
|
workerWait(t, injection.name+" acknowledged", 15*time.Second, func() bool {
|
|
return workerQueue(t) == "0:0"
|
|
})
|
|
after := waitAttachment(t, user, att.ID, "ready", 5*time.Second)
|
|
if !reflect.DeepEqual(ready, after) ||
|
|
workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") != jobID ||
|
|
workerSQL(t, "SELECT pipeline_version||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:1" ||
|
|
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where+" AND pipeline_version=1") != "0" ||
|
|
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where+" AND pipeline_version=2") != "3" ||
|
|
workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where) != "2" {
|
|
t.Fatalf("%s changed metadata or created extra work", injection.name)
|
|
}
|
|
for name, before := range content {
|
|
if !bytes.Equal(before, workerContent(t, user, att.ID, name)) {
|
|
t.Fatalf("%s changed %s bytes", injection.name, name)
|
|
}
|
|
}
|
|
}
|
|
t.Logf("PASS attachment=%s: v2 completed before v1 delivery; stale v1 and duplicate v2 acknowledged without changes", id)
|
|
}
|
|
|
|
func TestPipelineCrashBeforeWrite(t *testing.T) {
|
|
user := createUser(t)
|
|
chat := createChat(t, user, user.ID)
|
|
stopService(t, "worker")
|
|
if workerQueue(t) != "0:0" {
|
|
t.Fatal("run on an idle stand with an empty attachment queue")
|
|
}
|
|
att, source := workerUpload(t, user, chat.ID)
|
|
id := att.ID.String()
|
|
where := "attachment_id='" + id + "'"
|
|
jobID := workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'")
|
|
workerCommand(t, "compose", "run", "--rm", "--no-deps", "worker", "-upgrade", id)
|
|
|
|
// Original is the first result PUT. Neither it nor any variant reaches S3.
|
|
proxy, control := pipelineS3Gate(t, "/attachments/"+id)
|
|
testWorker := "pipeline-crash-" + uuid.NewString()
|
|
t.Cleanup(func() { workerCommand(t, "rm", "-f", testWorker) })
|
|
workerCommand(t, "compose", "run", "-d", "--no-deps", "--name", testWorker,
|
|
"-e", "WORKER_CONCURRENCY=1", "-e", "JOB_TIMEOUT_SECONDS=15",
|
|
"-e", "S3_ENDPOINT=http://"+proxy+":9000", "worker")
|
|
workerWait(t, "v2 held before first result PUT", 10*time.Second, func() bool {
|
|
return control("_state") == "1:0"
|
|
})
|
|
if workerSQL(t, "SELECT pipeline_version||':'||status||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:processing:1" ||
|
|
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where) != "0" {
|
|
t.Fatal("expected v2 processing without a committed result")
|
|
}
|
|
workerCommand(t, "kill", "--signal", "SIGKILL", testWorker)
|
|
// Kill the held request too: it must never be forwarded after the crash.
|
|
workerCommand(t, "kill", "--signal", "SIGKILL", proxy)
|
|
workerWait(t, "crashed v2 job returned to broker", 10*time.Second, func() bool {
|
|
return workerQueue(t) == "1:0"
|
|
})
|
|
compose(t, "start", "worker")
|
|
// Recovery must use the natural lease expiry; no status/lease SQL injection.
|
|
ready := waitAttachment(t, user, att.ID, "ready", 40*time.Second)
|
|
workerWait(t, "recovered v2 acknowledgement", 15*time.Second, func() bool {
|
|
return workerQueue(t) == "0:0"
|
|
})
|
|
if len(ready.Variants) != 3 ||
|
|
!bytes.Equal(workerContent(t, user, att.ID, "original"), source) ||
|
|
workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") != jobID ||
|
|
workerSQL(t, "SELECT pipeline_version||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:2" ||
|
|
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where+" AND pipeline_version=2") != "3" ||
|
|
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where) != "3" ||
|
|
workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+" AND pipeline_version=2 AND attempt=2 AND published_at IS NOT NULL") != "1" {
|
|
t.Fatal("crash recovery lost the accepted job or changed its identity or result")
|
|
}
|
|
for _, name := range []string{"thumbnail", "crop", "optimized"} {
|
|
if len(workerContent(t, user, att.ID, name)) == 0 {
|
|
t.Fatalf("recovered v2 has empty %s", name)
|
|
}
|
|
}
|
|
t.Logf("PASS attachment=%s: SIGKILL before first result PUT; natural lease recovery; same job ready on v2 attempt2", id)
|
|
}
|