lab4: компенсация без потери объекта при потере ответа COMMIT, полный декод изображений (sharp) в proxy и direct complete

This commit is contained in:
2026-10-23 16:37:13 +03:00
parent b32ce9a75d
commit 4badd5a7b9
33 changed files with 1932 additions and 861 deletions
+560 -1
View File
@@ -26,6 +26,7 @@
"redis": "^6.3.0",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"sharp": "^0.35.5",
"zod": "^4.6.5"
},
"devDependencies": {
@@ -553,6 +554,16 @@
"node": ">=0.1.90"
}
},
"node_modules/@emnapi/runtime": {
"version": "1.11.3",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz",
"integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==",
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@epic-web/invariant": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@epic-web/invariant/-/invariant-1.0.0.tgz",
@@ -1200,6 +1211,506 @@
"node": ">= 10"
}
},
"node_modules/@img/colour": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",
"integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/@img/sharp-darwin-arm64": {
"version": "0.35.5",
"resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz",
"integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==",
"cpu": [
"arm64"
],
"license": "Apache-2.0",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-darwin-arm64": "1.3.4"
}
},
"node_modules/@img/sharp-darwin-x64": {
"version": "0.35.5",
"resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz",
"integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==",
"cpu": [
"x64"
],
"license": "Apache-2.0",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-darwin-x64": "1.3.4"
}
},
"node_modules/@img/sharp-freebsd-wasm32": {
"version": "0.35.5",
"resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz",
"integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==",
"license": "Apache-2.0",
"optional": true,
"os": [
"freebsd"
],
"dependencies": {
"@img/sharp-wasm32": "0.35.5"
},
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-darwin-arm64": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz",
"integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==",
"cpu": [
"arm64"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"darwin"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-darwin-x64": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz",
"integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==",
"cpu": [
"x64"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"darwin"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linux-arm": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz",
"integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==",
"cpu": [
"arm"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linux-arm64": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz",
"integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==",
"cpu": [
"arm64"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linux-ppc64": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz",
"integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==",
"cpu": [
"ppc64"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linux-riscv64": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz",
"integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==",
"cpu": [
"riscv64"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linux-s390x": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz",
"integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==",
"cpu": [
"s390x"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linux-x64": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz",
"integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==",
"cpu": [
"x64"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linuxmusl-arm64": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz",
"integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==",
"cpu": [
"arm64"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linuxmusl-x64": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz",
"integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==",
"cpu": [
"x64"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-linux-arm": {
"version": "0.35.5",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz",
"integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==",
"cpu": [
"arm"
],
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linux-arm": "1.3.4"
}
},
"node_modules/@img/sharp-linux-arm64": {
"version": "0.35.5",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz",
"integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==",
"cpu": [
"arm64"
],
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linux-arm64": "1.3.4"
}
},
"node_modules/@img/sharp-linux-ppc64": {
"version": "0.35.5",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz",
"integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==",
"cpu": [
"ppc64"
],
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linux-ppc64": "1.3.4"
}
},
"node_modules/@img/sharp-linux-riscv64": {
"version": "0.35.5",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz",
"integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==",
"cpu": [
"riscv64"
],
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linux-riscv64": "1.3.4"
}
},
"node_modules/@img/sharp-linux-s390x": {
"version": "0.35.5",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz",
"integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==",
"cpu": [
"s390x"
],
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linux-s390x": "1.3.4"
}
},
"node_modules/@img/sharp-linux-x64": {
"version": "0.35.5",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz",
"integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==",
"cpu": [
"x64"
],
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linux-x64": "1.3.4"
}
},
"node_modules/@img/sharp-linuxmusl-arm64": {
"version": "0.35.5",
"resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz",
"integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==",
"cpu": [
"arm64"
],
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linuxmusl-arm64": "1.3.4"
}
},
"node_modules/@img/sharp-linuxmusl-x64": {
"version": "0.35.5",
"resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz",
"integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==",
"cpu": [
"x64"
],
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linuxmusl-x64": "1.3.4"
}
},
"node_modules/@img/sharp-wasm32": {
"version": "0.35.5",
"resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz",
"integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==",
"license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",
"optional": true,
"dependencies": {
"@emnapi/runtime": "^1.11.3"
},
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-webcontainers-wasm32": {
"version": "0.35.5",
"resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz",
"integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==",
"cpu": [
"wasm32"
],
"license": "Apache-2.0",
"optional": true,
"dependencies": {
"@img/sharp-wasm32": "0.35.5"
},
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-win32-arm64": {
"version": "0.35.5",
"resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz",
"integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==",
"cpu": [
"arm64"
],
"license": "Apache-2.0 AND LGPL-3.0-or-later",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-win32-ia32": {
"version": "0.35.5",
"resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz",
"integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==",
"cpu": [
"ia32"
],
"license": "Apache-2.0 AND LGPL-3.0-or-later",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": "^20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-win32-x64": {
"version": "0.35.5",
"resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz",
"integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==",
"cpu": [
"x64"
],
"license": "Apache-2.0 AND LGPL-3.0-or-later",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@inquirer/ansi": {
"version": "2.0.8",
"resolved": "https://registry.npmjs.org/@inquirer/ansi/-/ansi-2.0.8.tgz",
@@ -4014,7 +4525,6 @@
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
"integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
"dev": true,
"license": "Apache-2.0",
"engines": {
"node": ">=8"
@@ -6842,6 +7352,55 @@
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
"license": "ISC"
},
"node_modules/sharp": {
"version": "0.35.5",
"resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz",
"integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==",
"license": "Apache-2.0",
"dependencies": {
"@img/colour": "^1.1.0",
"detect-libc": "^2.1.2",
"semver": "^7.8.5"
},
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-darwin-arm64": "0.35.5",
"@img/sharp-darwin-x64": "0.35.5",
"@img/sharp-freebsd-wasm32": "0.35.5",
"@img/sharp-libvips-darwin-arm64": "1.3.4",
"@img/sharp-libvips-darwin-x64": "1.3.4",
"@img/sharp-libvips-linux-arm": "1.3.4",
"@img/sharp-libvips-linux-arm64": "1.3.4",
"@img/sharp-libvips-linux-ppc64": "1.3.4",
"@img/sharp-libvips-linux-riscv64": "1.3.4",
"@img/sharp-libvips-linux-s390x": "1.3.4",
"@img/sharp-libvips-linux-x64": "1.3.4",
"@img/sharp-libvips-linuxmusl-arm64": "1.3.4",
"@img/sharp-libvips-linuxmusl-x64": "1.3.4",
"@img/sharp-linux-arm": "0.35.5",
"@img/sharp-linux-arm64": "0.35.5",
"@img/sharp-linux-ppc64": "0.35.5",
"@img/sharp-linux-riscv64": "0.35.5",
"@img/sharp-linux-s390x": "0.35.5",
"@img/sharp-linux-x64": "0.35.5",
"@img/sharp-linuxmusl-arm64": "0.35.5",
"@img/sharp-linuxmusl-x64": "0.35.5",
"@img/sharp-webcontainers-wasm32": "0.35.5",
"@img/sharp-win32-arm64": "0.35.5",
"@img/sharp-win32-ia32": "0.35.5",
"@img/sharp-win32-x64": "0.35.5"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
}
}
},
"node_modules/shebang-command": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
+1
View File
@@ -44,6 +44,7 @@
"redis": "^6.3.0",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"sharp": "^0.35.5",
"zod": "^4.6.5"
},
"devDependencies": {
@@ -8,6 +8,8 @@ import { StorageModule } from '../storage/storage.module.js';
import { AttachmentSweeper } from './attachment-sweeper.service.js';
import { AttachmentsController } from './attachments.controller.js';
import { AttachmentsRepository } from './attachments.repository.js';
import { ImageDecoder } from './image/image-decoder.js';
import { UploadSlots } from './upload-slots.js';
import { DirectUploadsService } from './direct-uploads.service.js';
import { AttachmentsService } from './attachments.service.js';
@@ -25,6 +27,8 @@ import { AttachmentsService } from './attachments.service.js';
AttachmentsRepository,
AttachmentsService,
DirectUploadsService,
ImageDecoder,
UploadSlots,
AttachmentSweeper,
],
exports: [AttachmentsRepository],
+27 -2
View File
@@ -75,13 +75,38 @@ export class AttachmentsRepository {
);
}
async rejectPending(id: string): Promise<void> {
await this.database.query(
async rejectPending(id: string): Promise<boolean> {
const result = await this.database.query(
'attachments.reject_pending',
`UPDATE attachments SET status = 'rejected', updated_at = now()
WHERE id = $1 AND status = 'pending'`,
[id],
);
return result.rowCount === 1;
}
/**
* Takes a pending row out of play before its object is deleted. The object
* is deleted only when this returns true: a row that is already `ready`
* (its commit succeeded even if the reply was lost) keeps its object.
*/
async claimForCompensation(id: string): Promise<boolean> {
const result = await this.database.query(
'attachments.claim_for_compensation',
`UPDATE attachments SET status = 'deleting', updated_at = now()
WHERE id = $1 AND status = 'pending'`,
[id],
);
return result.rowCount === 1;
}
async findById(id: string): Promise<AttachmentRow | undefined> {
const result = await this.database.query<AttachmentRow>(
'attachments.find_by_id',
'SELECT * FROM attachments WHERE id = $1',
[id],
);
return result.rows[0];
}
async findVisible(
@@ -0,0 +1,113 @@
import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { Readable } from 'node:stream';
import { fileURLToPath } from 'node:url';
import { describe, expect, it, vi } from 'vitest';
import type { AttachmentRow } from './attachment.js';
import { AttachmentsService } from './attachments.service.js';
const here = dirname(fileURLToPath(import.meta.url));
const png = readFileSync(join(here, '../../../tests/fixtures/sample.png'));
const lostReply = () =>
Object.assign(new Error('Connection terminated unexpectedly'), {});
const settings: Record<string, number> = {
MAX_UPLOAD_BYTES: 10_485_760,
MAX_IMAGE_PIXELS: 40_000_000,
UPLOAD_TIMEOUT_MS: 10_000,
};
function setup(repository: Record<string, unknown>) {
const storage = {
objectKey: (id: string) => `attachments/${id}/original`,
putStream: vi.fn(async (_key: string, body: Readable) => {
for await (const _chunk of body) {
// drain like S3 does
}
}),
delete: vi.fn().mockResolvedValue(undefined),
};
const service = new AttachmentsService(
{ getOrThrow: (key: string) => settings[key] } as never,
{
insertPending: vi.fn(),
deleteClaimed: vi.fn(),
...repository,
} as never,
storage as never,
{ getForUser: vi.fn() } as never,
{ increment: vi.fn(), add: vi.fn() } as never,
{ verify: vi.fn() } as never,
{ run: (work: () => Promise<unknown>) => work() } as never,
);
const upload = () =>
service.uploadProxy(
'chat',
{ id: 'user' } as never,
'a.png',
'image/png',
String(png.length),
Readable.from([png]),
);
return { storage, upload };
}
const readyRow = (id: string): AttachmentRow => ({
id,
chat_id: 'chat',
owner_id: 'user',
filename: 'a.png',
content_type: 'image/png',
upload_mode: 'proxy',
status: 'ready',
object_key: `attachments/${id}/original`,
size_bytes: png.length,
sha256: 'a'.repeat(64),
width: 320,
height: 200,
expires_at: null,
created_at: new Date(),
updated_at: new Date(),
});
describe('AttachmentsService compensation', () => {
it('keeps the object and answers 201 when ready was committed but its reply was lost', async () => {
const { storage, upload } = setup({
markReady: vi.fn().mockRejectedValue(lostReply()),
claimForCompensation: vi.fn().mockResolvedValue(false),
findById: vi.fn((id: string) => Promise.resolve(readyRow(id))),
});
const attachment = await upload();
expect(attachment.status).toBe('ready');
expect(storage.delete).not.toHaveBeenCalled();
});
it('deletes nothing while PostgreSQL is unreachable', async () => {
const { storage, upload } = setup({
markReady: vi.fn().mockRejectedValue(lostReply()),
claimForCompensation: vi.fn().mockRejectedValue(lostReply()),
findById: vi.fn().mockRejectedValue(lostReply()),
});
await expect(upload()).rejects.toThrow();
expect(storage.delete).not.toHaveBeenCalled();
});
it('deletes the object only after claiming the pending row', async () => {
const order: string[] = [];
const { storage, upload } = setup({
markReady: vi.fn().mockRejectedValue(lostReply()),
claimForCompensation: vi.fn(async () => {
order.push('claim');
return true;
}),
deleteClaimed: vi.fn(async () => {
order.push('delete-row');
}),
});
storage.delete.mockImplementation(async () => {
order.push('delete-object');
});
await expect(upload()).rejects.toThrow();
expect(order).toEqual(['claim', 'delete-object', 'delete-row']);
});
});
+62 -23
View File
@@ -30,6 +30,8 @@ import {
ImageRejectedError,
} from './image/image-inspector.js';
import { AttachmentsRepository } from './attachments.repository.js';
import { ImageDecoder } from './image/image-decoder.js';
import { UploadSlots } from './upload-slots.js';
const MEDIA_TYPES = new Set(['image/png', 'image/jpeg']);
@@ -49,11 +51,9 @@ class UploadInterruptedError extends Error {}
@Injectable()
export class AttachmentsService {
private readonly logger = new Logger(AttachmentsService.name);
private inFlight = 0;
private readonly maxUploadBytes: number;
private readonly maxPixels: number;
private readonly uploadTimeoutMs: number;
private readonly maxInFlight: number;
constructor(
config: ConfigService<AppConfig>,
@@ -61,11 +61,12 @@ export class AttachmentsService {
private readonly storage: ObjectStorage,
private readonly chats: ChatsService,
private readonly metrics: MetricsService,
private readonly decoder: ImageDecoder,
private readonly slots: UploadSlots,
) {
this.maxUploadBytes = config.getOrThrow('MAX_UPLOAD_BYTES');
this.maxPixels = config.getOrThrow('MAX_IMAGE_PIXELS');
this.uploadTimeoutMs = config.getOrThrow('UPLOAD_TIMEOUT_MS');
this.maxInFlight = config.getOrThrow('UPLOAD_MAX_IN_FLIGHT');
}
async uploadProxy(
@@ -93,15 +94,9 @@ export class AttachmentsService {
if (contentLength > this.maxUploadBytes)
throw new PayloadTooLargeException('Image is too large');
if (this.inFlight >= this.maxInFlight)
throw new HttpException(
{ message: 'Too many concurrent uploads', retryAfter: 1 },
429,
);
this.inFlight += 1;
try {
return this.slots.run(async () => {
await this.chats.getForUser(chatId, user);
return await this.receive(
return this.receive(
chatId,
user,
filename,
@@ -109,9 +104,7 @@ export class AttachmentsService {
contentLength,
body,
);
} finally {
this.inFlight -= 1;
}
});
}
private async receive(
@@ -193,8 +186,12 @@ export class AttachmentsService {
});
const sha256 = createHash('sha256');
const decoder = this.decoder;
// Copy for the full decode check; bounded by MAX_UPLOAD_BYTES and
// UPLOAD_MAX_IN_FLIGHT, released as soon as the decode starts.
const copy: Buffer[] = [];
let total = 0;
const account = (chunk: Buffer, inspect: boolean): void => {
const account = (chunk: Buffer, inspect: boolean): boolean => {
total += chunk.length;
if (total > contentLength)
throw new UploadInterruptedError(
@@ -203,19 +200,26 @@ export class AttachmentsService {
if (inspect) inspector.push(chunk);
sha256.update(chunk);
this.metrics.add('attachments.proxy.bytes_in', chunk.length);
// Validate before the last bytes reach S3: it cannot commit an
// object whose body is incomplete.
if (total === contentLength) inspector.finish();
copy.push(chunk);
return total === contentLength;
};
// Validate before the last bytes reach S3: it cannot commit an object
// whose body is incomplete, so an invalid image never becomes an object.
const finalize = async (): Promise<void> => {
inspector.finish();
const data = Buffer.concat(copy, total);
copy.length = 0;
await decoder.verify(data);
};
async function* generate(): AsyncGenerator<Buffer> {
for (const chunk of head) {
account(chunk, false);
if (account(chunk, false)) await finalize();
yield chunk;
}
for (;;) {
const step = await next();
if (step.done) break;
account(step.value, true);
if (account(step.value, true)) await finalize();
yield step.value;
}
if (total < contentLength)
@@ -238,6 +242,7 @@ export class AttachmentsService {
// `rejection`; the listener also keeps a late error from crashing us.
readable.on('error', () => controller.abort());
let claimed = false;
let stored = false;
try {
await this.storage.putStream(
key,
@@ -250,6 +255,7 @@ export class AttachmentsService {
'attachments.proxy.bytes_to_s3',
contentLength,
);
stored = true;
const row = await this.repository.markReady(id, {
sizeBytes: total,
sha256: sha256.digest('hex'),
@@ -264,7 +270,23 @@ export class AttachmentsService {
return toAttachment(row);
} catch (error) {
readable.destroy();
if (!claimed) await this.compensate(id, key);
if (!claimed) {
const outcome = await this.compensate(id, key);
// markReady failed on our side, but the row is no longer
// pending: the commit may have succeeded with its reply lost.
// If so, the upload is complete and 201 is the truth.
if (outcome === 'not_pending' && stored) {
const row = await this.repository
.findById(id)
.catch(() => undefined);
if (row?.status === 'ready') {
this.metrics.increment(
'attachments.upload.recovered',
);
return toAttachment(row);
}
}
}
throw this.mapUploadError(rejection ?? error, timedOut);
}
} finally {
@@ -279,16 +301,33 @@ export class AttachmentsService {
return error;
}
async compensate(id: string, key: string): Promise<void> {
/**
* Undoes an upload that did not reach `ready`. The row is claimed first
* (pending -> deleting) and the object is deleted only after a successful
* claim: if PostgreSQL committed `ready` but the reply was lost, the claim
* matches nothing and the object stays. If PostgreSQL is unreachable,
* nothing is deleted; the sweeper finishes the job after expiry + grace
* (a row stuck in `deleting` is re-claimed after a minute).
*/
async compensate(
id: string,
key: string,
): Promise<'compensated' | 'not_pending' | 'deferred'> {
try {
if (!(await this.repository.claimForCompensation(id))) {
this.metrics.increment('attachments.compensation_skipped');
return 'not_pending';
}
await this.storage.delete(key);
await this.repository.deletePending(id);
await this.repository.deleteClaimed(id);
this.metrics.increment('attachments.compensated');
return 'compensated';
} catch (error) {
this.metrics.increment('attachments.compensation_deferred');
this.logger.warn(
`Compensation of attachment ${id} deferred: ${error instanceof Error ? error.message : 'unknown error'}`,
);
return 'deferred';
}
}
+43 -36
View File
@@ -22,8 +22,9 @@ import { AttachmentsRepository } from './attachments.repository.js';
import { imageRejection } from './attachments.service.js';
import type { CreateDirectUploadDto } from './dto/create-direct-upload.dto.js';
import { validateFilename } from './filename.js';
import { ImageDecoder } from './image/image-decoder.js';
import { UploadSlots } from './upload-slots.js';
import {
IMAGE_HEADER_MAX_BYTES,
ImageInspector,
ImageRejectedError,
type ImageHeader,
@@ -37,7 +38,6 @@ export type DirectUpload = {
expires_at: string;
};
const FIRST_RANGE_BYTES = 65_536;
const MEDIA_TYPES = new Set(['image/png', 'image/jpeg']);
@Injectable()
@@ -53,6 +53,8 @@ export class DirectUploadsService {
private readonly storage: ObjectStorage,
private readonly chats: ChatsService,
private readonly metrics: MetricsService,
private readonly decoder: ImageDecoder,
private readonly slots: UploadSlots,
) {
this.maxUploadBytes = config.getOrThrow('MAX_UPLOAD_BYTES');
this.maxPixels = config.getOrThrow('MAX_IMAGE_PIXELS');
@@ -136,7 +138,10 @@ export class DirectUploadsService {
);
if (!row) throw new NotFoundException();
if (row.status === 'ready') return toAttachment(row);
return this.slots.run(() => this.verifyAndMarkReady(row));
}
private async verifyAndMarkReady(row: AttachmentRow): Promise<Attachment> {
const size = Number(row.size_bytes);
const expectedChecksum = Buffer.from(
row.sha256 as string,
@@ -152,10 +157,9 @@ export class DirectUploadsService {
);
}
// Only the header is read: the signed checksum already pins every byte.
let header: ImageHeader;
try {
header = await this.readHeader(row.object_key, size);
header = await this.verifyObject(row.object_key, size);
} catch (error) {
if (error instanceof ImageRejectedError) {
await this.reject(row);
@@ -181,40 +185,41 @@ export class DirectUploadsService {
}
/**
* Reads a small first range and widens it only when the header is not in it,
* so the usual `complete` costs one short ranged GET. A range that covers the
* whole object is also checked for structural completeness.
* Reads the whole object: a correct signed checksum only proves that the
* bytes are the ones the client declared, not that they form an image. The
* stream goes through ImageInspector (structure, CRCs, completeness), then
* the copy is fully decoded. Memory is bounded like a proxy upload.
*/
private async readHeader(key: string, size: number): Promise<ImageHeader> {
const ceiling = Math.min(size, IMAGE_HEADER_MAX_BYTES);
let range = Math.min(size, FIRST_RANGE_BYTES);
for (;;) {
const inspector = new ImageInspector(this.maxPixels);
const stream = await this.storage.getStream(
key,
`bytes=0-${range - 1}`,
);
if (stream === null)
throw new ConflictException('Upload has not been received');
let verified = 0;
try {
for await (const chunk of stream as AsyncIterable<Buffer>) {
verified += chunk.length;
inspector.push(chunk);
}
} finally {
stream.destroy();
this.metrics.add('attachments.direct.verify_bytes', verified);
private async verifyObject(
key: string,
size: number,
): Promise<ImageHeader> {
const stream = await this.storage.getStream(key);
if (stream === null)
throw new ConflictException('Upload has not been received');
const inspector = new ImageInspector(this.maxPixels);
const chunks: Buffer[] = [];
let read = 0;
try {
for await (const chunk of stream as AsyncIterable<Buffer>) {
read += chunk.length;
if (read > size)
throw new ImageRejectedError(
'unsupported_media_type',
'Object is larger than declared',
);
inspector.push(chunk);
chunks.push(chunk);
}
if (range === size) return inspector.finish();
if (inspector.header !== undefined) return inspector.header;
if (range >= ceiling)
throw new ImageRejectedError(
'unsupported_media_type',
'Image header is missing',
);
range = ceiling;
} finally {
stream.destroy();
this.metrics.add('attachments.direct.verify_bytes', read);
}
const header = inspector.finish();
const data = Buffer.concat(chunks, read);
chunks.length = 0;
await this.decoder.verify(data);
return header;
}
/**
@@ -223,7 +228,9 @@ export class DirectUploadsService {
* object that no row refers to. The sweeper removes both after expiry + grace.
*/
private async reject(row: AttachmentRow): Promise<void> {
await this.repository.rejectPending(row.id);
// Row first: a row that is not pending any more (ready after a parallel
// complete, or claimed by the sweeper) keeps its object.
if (!(await this.repository.rejectPending(row.id))) return;
try {
await this.storage.delete(row.object_key);
} catch {
@@ -0,0 +1,51 @@
import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';
import { jpegWithoutScanData } from '../../../test/support/jpeg.js';
import { noisePng, pngWithGarbageIdat } from '../../../test/support/png.js';
import { ImageDecoder } from './image-decoder.js';
import { ImageInspector, ImageRejectedError } from './image-inspector.js';
const here = dirname(fileURLToPath(import.meta.url));
const png = readFileSync(join(here, '../../../../tests/fixtures/sample.png'));
const jpeg = readFileSync(join(here, '../../../test/fixtures/sample.jpg'));
const progressive = readFileSync(
join(here, '../../../test/fixtures/sample-progressive.jpg'),
);
const settings: Record<string, number> = {
MAX_IMAGE_PIXELS: 40_000_000,
IMAGE_DECODE_MAX_CONCURRENT: 1,
};
const decoder = new ImageDecoder(
{ getOrThrow: (key: string) => settings[key] } as never,
{ increment: () => undefined, add: () => undefined } as never,
);
describe('ImageDecoder', () => {
it('accepts valid PNG and JPEG files, also concurrently', async () => {
await Promise.all(
[png, jpeg, progressive, noisePng(1_048_576)].map((data) =>
decoder.verify(data),
),
);
});
// These files pass the structural inspector; only a decode catches them.
it.each([
['PNG with a garbage zlib stream', pngWithGarbageIdat()],
['JPEG without scan data', jpegWithoutScanData(jpeg)],
[
'progressive JPEG without scan data',
jpegWithoutScanData(progressive),
],
])('rejects a %s', async (_name, data) => {
const inspector = new ImageInspector(40_000_000);
inspector.push(data);
expect(inspector.finish().width).toBe(320);
await expect(decoder.verify(data)).rejects.toBeInstanceOf(
ImageRejectedError,
);
});
});
@@ -0,0 +1,72 @@
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import sharp from 'sharp';
import type { AppConfig } from '../../config/app-config.schema.js';
import { MetricsService } from '../../metrics/metrics.service.js';
import { ImageRejectedError } from './image-inspector.js';
// One libvips worker per decode and no operation cache: decodes are one-off,
// and memory must stay predictable under the per-replica limit.
sharp.cache(false);
sharp.concurrency(1);
/**
* Full decode check. ImageInspector only proves the container structure
* (signature, chunk CRCs, markers, dimensions); a PNG with a garbage zlib stream
* or a JPEG without scan data passes it. Decoding every pixel with
* failOn=warning rejects those, including truncated or corrupted entropy data.
* Decodes are bounded by IMAGE_DECODE_MAX_CONCURRENT; callers wait for a slot.
*/
@Injectable()
export class ImageDecoder {
private readonly maxPixels: number;
private readonly maxConcurrent: number;
private active = 0;
private readonly waiting: (() => void)[] = [];
constructor(
config: ConfigService<AppConfig>,
private readonly metrics: MetricsService,
) {
this.maxPixels = config.getOrThrow('MAX_IMAGE_PIXELS');
this.maxConcurrent = config.getOrThrow('IMAGE_DECODE_MAX_CONCURRENT');
}
async verify(data: Buffer): Promise<void> {
await this.acquire();
const started = performance.now();
try {
await sharp(data, {
failOn: 'warning',
sequentialRead: true,
limitInputPixels: this.maxPixels,
}).stats();
} catch {
this.metrics.increment('attachments.decode.rejected');
throw new ImageRejectedError(
'unsupported_media_type',
'Image data cannot be decoded',
);
} finally {
this.metrics.add(
'attachments.decode.ms',
performance.now() - started,
);
this.release();
}
}
private async acquire(): Promise<void> {
if (this.active < this.maxConcurrent) {
this.active += 1;
return;
}
await new Promise<void>((resolve) => this.waiting.push(resolve));
}
private release(): void {
const next = this.waiting.shift();
if (next) next();
else this.active -= 1;
}
}
+3 -1
View File
@@ -59,7 +59,9 @@ function unsupported(message: string): ImageRejectedError {
/**
* Streaming structural validator for PNG and JPEG. It never buffers the body:
* only fixed-size fields (chunk headers, IHDR, SOF) are accumulated, and
* nothing is decompressed.
* nothing is decompressed. It is the early gate (type, dimensions, pixel limit
* before anything is stored), not proof of a valid image: compressed pixel
* data is checked by ImageDecoder.
*/
export class ImageInspector {
private state: State = 'start';
+31
View File
@@ -0,0 +1,31 @@
import { HttpException, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import type { AppConfig } from '../config/app-config.schema.js';
/**
* Per-replica cap on requests that hold an image in memory (proxy upload,
* direct complete): each may keep up to MAX_UPLOAD_BYTES for the decode check.
*/
@Injectable()
export class UploadSlots {
private inFlight = 0;
private readonly max: number;
constructor(config: ConfigService<AppConfig>) {
this.max = config.getOrThrow('UPLOAD_MAX_IN_FLIGHT');
}
async run<T>(work: () => Promise<T>): Promise<T> {
if (this.inFlight >= this.max)
throw new HttpException(
{ message: 'Too many concurrent uploads', retryAfter: 1 },
429,
);
this.inFlight += 1;
try {
return await work();
} finally {
this.inFlight -= 1;
}
}
}
+7 -1
View File
@@ -85,7 +85,13 @@ export const appConfigSchema = z
MAX_UPLOAD_BYTES: numeric('MAX_UPLOAD_BYTES', 1, 10485760, 10485760),
MAX_IMAGE_PIXELS: numeric('MAX_IMAGE_PIXELS', 1, 40000000, 40000000),
UPLOAD_TIMEOUT_MS: numeric('UPLOAD_TIMEOUT_MS', 1000, undefined, 25000),
UPLOAD_MAX_IN_FLIGHT: numeric('UPLOAD_MAX_IN_FLIGHT', 1, 1024, 32),
UPLOAD_MAX_IN_FLIGHT: numeric('UPLOAD_MAX_IN_FLIGHT', 1, 1024, 16),
IMAGE_DECODE_MAX_CONCURRENT: numeric(
'IMAGE_DECODE_MAX_CONCURRENT',
1,
64,
2,
),
// 0 отключает фоновый проход уборщика (остаётся ручной CLI).
ATTACHMENT_SWEEP_INTERVAL_MS: numeric(
'ATTACHMENT_SWEEP_INTERVAL_MS',
+27 -1
View File
@@ -21,7 +21,13 @@ import {
upload,
uploadRaw,
} from './support/e2e.js';
import { noisePng, padPngTo, pixelBombPng } from './support/png.js';
import { jpegWithoutScanData } from './support/jpeg.js';
import {
noisePng,
padPngTo,
pixelBombPng,
pngWithGarbageIdat,
} from './support/png.js';
const png = readFileSync(
new URL('../../tests/fixtures/sample.png', import.meta.url),
@@ -167,6 +173,8 @@ describe('attachments (proxy upload)', () => {
flipped,
Buffer.concat([png.subarray(0, 8), randomBytes(2048)]),
Buffer.alloc(0),
// Structure and CRCs are fine; the pixel data does not decode.
pngWithGarbageIdat(),
];
for (const data of cases)
expectError(
@@ -176,6 +184,24 @@ describe('attachments (proxy upload)', () => {
);
});
it.each([
['baseline', jpeg],
['progressive', progressive],
])('rejects a %s JPEG without scan data', async (_name, data) => {
expectError(
await upload(
alice.token,
leftoverChatId,
jpegWithoutScanData(data),
{
contentType: 'image/jpeg',
},
),
415,
'unsupported_media_type',
);
});
it('rejects a content type that does not match the bytes', async () => {
const gif = Buffer.from('GIF89a' + 'x'.repeat(64));
const cases: [Buffer, string][] = [
+24 -11
View File
@@ -944,12 +944,13 @@ describe.skipIf(!enabled)('dependency outages', () => {
expect((await request('/health/ready')).response.status).toBe(
200,
);
// Compensation could not reach S3, so the row stays for the sweeper.
// Compensation claimed the row but could not delete the object:
// the row stays in `deleting`, tracked for the sweeper.
expect(
await psql(
`select count(*) from attachments where chat_id = '${chat.id}' and status = 'pending' and filename = 's3down-${runId}.png'`,
`select status from attachments where chat_id = '${chat.id}' and filename = 's3down-${runId}.png'`,
),
).toBe('1');
).toBe('deleting');
} finally {
await compose('start', s3Service);
}
@@ -966,18 +967,27 @@ describe.skipIf(!enabled)('dependency outages', () => {
const after = await upload(samplePng, `s3after-${runId}.png`);
expect(after.response.status).toBe(201);
const filter = `chat_id = '${chat.id}' and status = 'pending' and filename = 's3down-${runId}.png'`;
await waitUntilExpired(filter);
await sweepNow();
expect(
await psql(`select count(*) from attachments where ${filter}`),
).toBe('0');
// A `deleting` row is re-claimed one minute after its last change
// (an in-flight compensation is never raced), then swept.
const filter = `chat_id = '${chat.id}' and filename = 's3down-${runId}.png'`;
await waitFor(
async () => {
await sweepNow();
return (
(await psql(
`select count(*) from attachments where ${filter}`,
)) === '0'
);
},
async () => 'deleting row was not swept',
90_000,
);
},
outagedRequestBudgetMs,
);
it(
'compensates the S3 write when PostgreSQL fails before ready',
'keeps the object while PostgreSQL is down before ready and sweeps it afterwards',
async () => {
const data = noisePng(1024 * 1024);
const filename = `pgfault-${runId}.png`;
@@ -1017,13 +1027,16 @@ describe.skipIf(!enabled)('dependency outages', () => {
`select object_key from attachments where ${filter}`,
);
expect(key).toMatch(/^attachments\/[0-9a-f-]{36}\/original$/u);
expect(await objectExists(key)).toBe(false);
// Without PostgreSQL the API cannot tell a lost commit from a failed
// one, so it deletes nothing; the pending row keeps the object tracked.
expect(await objectExists(key)).toBe(true);
await waitUntilExpired(filter);
await sweepNow();
expect(
await psql(`select count(*) from attachments where ${filter}`),
).toBe('0');
expect(await objectExists(key)).toBe(false);
},
outagedRequestBudgetMs,
);
+29 -1
View File
@@ -18,7 +18,7 @@ import {
json,
postMessage,
} from './support/e2e.js';
import { pixelBombPng } from './support/png.js';
import { noisePng, pixelBombPng } from './support/png.js';
const png = readFileSync(
new URL('../../tests/fixtures/sample.png', import.meta.url),
@@ -243,6 +243,34 @@ describe('direct upload (presigned PUT)', () => {
);
});
it.each([
['truncated PNG', () => png.subarray(0, png.length - 100)],
[
'PNG damaged after the first 64 KiB',
() => {
const data = noisePng(1_048_576);
data[700_000] ^= 0xff;
return data;
},
],
])('rejects a %s even with a matching checksum', async (_name, make) => {
// The declaration and the signed checksum match the bytes exactly:
// only a check of the whole image can tell they are not an image.
const data = make();
const ticket = await initOk(data);
expect((await put(ticket, data)).status).toBe(200);
expectError(
await complete(alice.token, ticket.attachment_id),
415,
'unsupported_media_type',
);
expectError(
await complete(alice.token, ticket.attachment_id),
404,
'not_found',
);
});
it('rejects a pixel bomb on complete', async () => {
const bomb = pixelBombPng();
const ticket = await initOk(bomb);
+10
View File
@@ -0,0 +1,10 @@
/** Keeps every segment through the SOS header and drops the scan data. */
export function jpegWithoutScanData(jpeg: Buffer): Buffer {
let offset = 2;
for (;;) {
const marker = jpeg[offset + 1];
offset += 2 + jpeg.readUInt16BE(offset + 2);
if (marker === 0xda) break;
}
return Buffer.concat([jpeg.subarray(0, offset), Buffer.from([0xff, 0xd9])]);
}
+11
View File
@@ -93,3 +93,14 @@ export function noisePng(size: number): Buffer {
return padPngTo(png, size);
}
}
/** Valid signature, IHDR, CRCs and IEND around a zlib stream of random bytes. */
export function pngWithGarbageIdat(): Buffer {
return buildPng({
width: 320,
height: 200,
colorType: 2,
bitDepth: 8,
idat: randomBytes(5000),
});
}