Compare commits

...

40 Commits

Author SHA1 Message Date
Tim Neutkens
fb2029c464 Publish
- @now/build-utils@0.4.32-canary.1
 - @now/next@0.0.82-canary.0
 - @now/node-server@0.4.26-canary.2
 - @now/node@0.4.28-canary.1
 - @now/php@0.4.13-canary.1
2018-12-17 00:11:08 +01:00
Tim Neutkens
3b15755054 Add heap increase to now/next (#134) 2018-12-17 00:05:41 +01:00
Igor Klopov
4f65cc3aa8 now/build-utils: catch per-file stream errors 2018-12-16 03:17:04 +03:00
Igor Klopov
9936e35280 tests: retry on ETIMEDOUT 2018-12-15 21:55:55 +03:00
Igor Klopov
a04fd242b8 Revert "now/php: create php engine outside of request handling"
This reverts commit a7c2d9648a.
2018-12-12 01:09:12 +03:00
Igor Klopov
17bc6174a9 now/php: a regression test for engine reusage 2018-12-12 00:49:38 +03:00
Igor Klopov
a7c2d9648a now/php: create php engine outside of request handling 2018-12-11 23:04:47 +03:00
Igor Klopov
faa5ea9e21 now/php: fix $HTTP_RAW_POST_DATA 2018-12-11 08:49:45 +03:00
Igor Klopov
c52f30c898 now/php: fix $_SERVER['HTTP_HEADER'] 2018-12-11 07:53:46 +03:00
Igor Klopov
d675edf1dc this fixes several-values-per-header-name issue + test (#129) 2018-12-11 03:12:43 +03:00
Anthony Mittaz
f85c4f496f Bump ncc to v0.5.3 (#128)
* Bump `ncc` to v0.5.3

* Also bump `ncc` to v0.5.3 in now-node
2018-12-10 14:11:23 -08:00
Nathan Rajlich
d52d7904c2 Publish
- @now/bash@0.0.4-canary.0
2018-12-10 11:07:34 -08:00
Nathan Rajlich
79232024bd [now-bash] Rename serve function to handler (#125)
This is more consistent with what you would expect for a lambda
function, and we should maintain that convention.

For example: https://github.com/gkrizek/bash-lambda-layer
2018-12-10 10:55:38 -08:00
Igor Klopov
660b787bc3 tests: print headers in deploymentPost too 2018-12-10 06:34:21 +03:00
Igor Klopov
2dbf983ddb tests: account API_HOST in fetchApi, not in fetchWithAuth 2018-12-10 06:19:42 +03:00
Igor Klopov
0866ba9391 tests: export fetchApi and fetchWithAuth 2018-12-10 05:45:46 +03:00
Igor Klopov
d259a722a0 [test] print resp.headers on filePost failure 2018-12-10 05:10:32 +03:00
Igor Klopov
bf77c51f64 tests: retry on some network failures 2018-12-10 03:59:13 +03:00
Igor Klopov
062b78130c Publish
- @now/build-utils@0.4.32-canary.0
 - @now/mdx-deck@0.4.18-canary.0
 - @now/node-server@0.4.26-canary.1
 - @now/php@0.4.13-canary.0
2018-12-10 02:38:22 +03:00
Igor Klopov
fa70bc50cb sema around await streamToBuffer(zipFile.outputStream) (#124)
* sema around await streamToBuffer(zipFile.outputStream)

* lint fixes

* fix looking for 'undefined' scriptName
2018-12-10 02:30:16 +03:00
Igor Klopov
08e22b35d1 now/node-server: an improvement for 09-no-bundle 2018-12-09 00:32:15 +03:00
Igor Klopov
9d8f3315a1 now/php: partially revert set-cookie commit 2018-12-09 00:31:29 +03:00
Igor Klopov
a737a99a9d now/php: new test for setcookie + fix for bridge.go 2018-12-09 00:08:54 +03:00
Igor Klopov
ee92d92c9f now/php: fixed $_REQUEST 2018-12-08 07:58:08 +03:00
Igor Klopov
34d3ebd289 now/php: fix $_SERVER['SERVER_PROTOCOL'] 2018-12-08 06:35:46 +03:00
Igor Klopov
785f187e5d now/php: unescape cookie values 2018-12-08 06:25:39 +03:00
Igor Klopov
44449f474e now/php: fixed $_COOKIE 2018-12-08 01:03:18 +03:00
Igor Klopov
f44dae7f39 now/php: lint fixes 2018-12-07 23:06:45 +03:00
Igor Klopov
06f973f641 now/php: fixed $_SERVER['REQUEST_METHOD'] 2018-12-07 23:04:47 +03:00
Igor Klopov
47bb47804e now/php: fixed $_POST 2018-12-07 22:52:11 +03:00
António Nuno Monteiro
5df692979a Provide a complete implementation for @now/mdx-deck's analyze function (#97)
* Provide a complete implementation for `@now/mdx-deck`'s analyze function

Fixes #93

* Delete the analyze step
2018-12-07 03:44:56 +03:00
Igor Klopov
cd02d5390f now/php: simplify test.go and test.php 2018-12-07 03:37:25 +03:00
Igor Klopov
c93fd416c4 tests: pass 'env' from now.json to nowDeploy 2018-12-07 02:45:12 +03:00
Igor Klopov
431db7a62d bridge.go: remove duplicating 'host' header check 2018-12-07 02:40:09 +03:00
Igor Klopov
6f86c70313 now/php: use v[len(v) - 1] instead of iterating 2018-12-07 02:13:28 +03:00
Igor Klopov
0923fc9200 now/php: better parsing of _GET 2018-12-07 02:05:25 +03:00
Igor Klopov
787675f462 probe.js for more complex tests. probe.js for now/php globals 2018-12-06 20:53:41 +03:00
Igor Klopov
977615720a improvements and a test for now/php 2018-12-06 08:23:12 +03:00
Igor Klopov
1a4e64cd27 Publish
- @now/node-server@0.4.26-canary.0
 - @now/node@0.4.28-canary.0
2018-12-06 04:16:39 +03:00
Igor Klopov
c9fc255002 don't force set NODE_ENV=production. default instead (#120) 2018-12-06 03:03:02 +03:00
45 changed files with 518 additions and 175 deletions

View File

@@ -31,6 +31,7 @@
"@types/glob": "^7.1.1",
"@types/multistream": "^2.1.1",
"@types/node": "^10.12.8",
"async-retry": "1.2.3",
"buffer-replace": "^1.0.0",
"eslint": "^5.9.0",
"eslint-config-airbnb-base": "^13.1.0",

View File

@@ -33,9 +33,9 @@ if declare -f build > /dev/null; then
build "$@"
fi
# Ensure the entrypoint defined a `serve` function
if ! declare -f serve > /dev/null; then
echo "ERROR: A \`serve\` function must be defined in \"$ENTRYPOINT\"!" >&2
# Ensure the entrypoint defined a `handler` function
if ! declare -f handler > /dev/null; then
echo "ERROR: A \`handler\` function must be defined in \"$ENTRYPOINT\"!" >&2
exit 1
fi

View File

@@ -1,6 +1,6 @@
{
"name": "@now/bash",
"version": "0.0.3",
"version": "0.0.4-canary.0",
"description": "Now 2.0 builder for HTTP endpoints written in Bash",
"main": "index.js",
"author": "Nathan Rajlich <nate@zeit.co>",

View File

@@ -49,7 +49,7 @@ _lambda_runtime_next() {
local exit_code=0
REQUEST="$event"
# Stdin of the `serve` function is the HTTP request body.
# Stdin of the `handler` function is the HTTP request body.
# Need to use a fifo here instead of bash <() because Lambda
# errors with "/dev/fd/63 not found" for some reason :/
local stdin
@@ -57,7 +57,7 @@ _lambda_runtime_next() {
mkfifo "$stdin"
_lambda_runtime_body "$event" > "$stdin" &
serve "$event" < "$stdin" > "$body" || exit_code="$?"
handler "$event" < "$stdin" > "$body" || exit_code="$?"
rm -f "$event" "$stdin"
if [ "$exit_code" -eq 0 ]; then

View File

@@ -35,7 +35,7 @@ async function scanParentDirs(destPath, scriptName) {
// eslint-disable-next-line no-await-in-loop
const packageJson = JSON.parse(await fs.readFile(packageJsonPath));
hasScript = Boolean(
packageJson.scripts && packageJson.scripts[scriptName],
packageJson.scripts && scriptName && packageJson.scripts[scriptName],
);
// eslint-disable-next-line no-await-in-loop
hasPackageLockJson = await fs.exists(

View File

@@ -1,4 +1,5 @@
const assert = require('assert');
const Sema = require('async-sema');
const { ZipFile } = require('yazl');
const streamToBuffer = require('./fs/stream-to-buffer.js');
@@ -14,6 +15,7 @@ class Lambda {
}
}
const sema = new Sema(10);
const mtime = new Date(1540000000000);
async function createLambda({
@@ -23,24 +25,33 @@ async function createLambda({
assert(typeof handler === 'string', '"handler" is not a string');
assert(typeof runtime === 'string', '"runtime" is not a string');
assert(typeof environment === 'object', '"environment" is not an object');
const zipFile = new ZipFile();
Object.keys(files)
.sort()
.forEach((name) => {
const file = files[name];
const stream = file.toStream();
zipFile.addReadStream(stream, name, { mode: file.mode, mtime });
await sema.acquire();
try {
const zipFile = new ZipFile();
const zipBuffer = await new Promise((resolve, reject) => {
Object.keys(files)
.sort()
.forEach((name) => {
const file = files[name];
const stream = file.toStream();
stream.on('error', reject);
zipFile.addReadStream(stream, name, { mode: file.mode, mtime });
});
zipFile.end();
streamToBuffer(zipFile.outputStream).then(resolve).catch(reject);
});
zipFile.end();
const zipBuffer = await streamToBuffer(zipFile.outputStream);
return new Lambda({
zipBuffer,
handler,
runtime,
environment,
});
return new Lambda({
zipBuffer,
handler,
runtime,
environment,
});
} finally {
sema.release();
}
}
module.exports = {

View File

@@ -1,6 +1,6 @@
{
"name": "@now/build-utils",
"version": "0.4.31",
"version": "0.4.32-canary.1",
"dependencies": {
"async-retry": "1.2.3",
"async-sema": "2.1.4",

View File

@@ -6,8 +6,6 @@ const glob = require('@now/build-utils/fs/glob.js');
const path = require('path');
const { runNpmInstall } = require('@now/build-utils/fs/run-user-scripts.js');
exports.analyze = ({ files, entrypoint }) => files[entrypoint].digest;
const writeFile = promisify(fs.writeFile);
exports.build = async ({ files, entrypoint, workPath }) => {

View File

@@ -1,6 +1,6 @@
{
"name": "@now/mdx-deck",
"version": "0.4.17",
"version": "0.4.18-canary.0",
"peerDependencies": {
"@now/build-utils": ">=0.0.1"
},

View File

@@ -1,6 +1,6 @@
{
"name": "@now/next",
"version": "0.0.81",
"version": "0.0.82-canary.0",
"dependencies": {
"@now/node-bridge": "0.1.4",
"execa": "^1.0.0",

View File

@@ -164,7 +164,7 @@ function normalizePackageJson(defaultPackageJson = {}) {
},
scripts: {
...defaultPackageJson.scripts,
'now-build': 'next build --lambdas',
'now-build': 'NODE_OPTIONS=--max_old_space_size=3000 next build --lambdas',
},
};
}

View File

@@ -47,7 +47,7 @@ async function downloadInstallAndBundle(
'package.json': new FileBlob({
data: JSON.stringify({
dependencies: {
'@zeit/ncc': '0.4.1',
'@zeit/ncc': '0.5.3',
},
}),
}),

View File

@@ -12,7 +12,10 @@ Server.prototype.listen = function listen(...args) {
};
try {
process.env.NODE_ENV = 'production';
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = 'production';
}
// PLACEHOLDER
} catch (error) {
console.error(error);

View File

@@ -1,6 +1,6 @@
{
"name": "@now/node-server",
"version": "0.4.25",
"version": "0.4.26-canary.2",
"dependencies": {
"@now/node-bridge": "^0.1.9",
"fs-extra": "7.0.1"

View File

@@ -5,7 +5,7 @@
{ "src": "without-bundle/index.js", "use": "@now/node-server", "config": { "bundle": false } }
],
"probes": [
{ "path": "/with-bundle", "mustContain": "RANDOMNESS_PLACEHOLDER" },
{ "path": "/without-bundle", "mustContain": "RANDOMNESS_PLACEHOLDER" }
{ "path": "/with-bundle", "mustContain": "RANDOMNESS_PLACEHOLDER:with-bundle" },
{ "path": "/without-bundle", "mustContain": "RANDOMNESS_PLACEHOLDER:without-bundle" }
]
}

View File

@@ -2,7 +2,7 @@ const http = require('http');
const isBundled = require('./is-bundled.js');
const server = http.createServer((req, resp) => {
resp.end(isBundled() ? 'RANDOMNESS_PLACEHOLDER' : '');
resp.end(isBundled() ? 'RANDOMNESS_PLACEHOLDER:with-bundle' : '');
});
server.listen();

View File

@@ -2,7 +2,7 @@ const http = require('http');
const isBundled = require('./is-bundled.js');
const server = http.createServer((req, resp) => {
resp.end(isBundled() ? '' : 'RANDOMNESS_PLACEHOLDER');
resp.end(isBundled() ? '' : 'RANDOMNESS_PLACEHOLDER:without-bundle');
});
server.listen();

View File

@@ -45,7 +45,7 @@ async function downloadInstallAndBundle(
'package.json': new FileBlob({
data: JSON.stringify({
dependencies: {
'@zeit/ncc': '0.4.1',
'@zeit/ncc': '0.5.3',
},
}),
}),

View File

@@ -6,7 +6,10 @@ bridge.port = 3000;
let listener;
try {
process.env.NODE_ENV = 'production';
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = 'production';
}
// PLACEHOLDER
} catch (error) {
console.error(error);

View File

@@ -1,6 +1,6 @@
{
"name": "@now/node",
"version": "0.4.27",
"version": "0.4.28-canary.1",
"dependencies": {
"@now/node-bridge": "^0.1.9",
"fs-extra": "7.0.1"

Binary file not shown.

View File

@@ -16,7 +16,7 @@ COPY ./utils/bridge.go /root/go/app/utils/bridge.go
COPY ./launcher.go /root/go/app/launcher.go
COPY ./php.ini /root/go/app/php.ini
COPY ./test.go /root/go/app/test.go
COPY ./test.php /root/go/app/public/test.php
COPY ./test.php /root/go/app/test.php
COPY ./test.sh /root/go/app/test.sh
RUN GOOS=linux GOARCH=amd64 CGO_ENABLED=1 go build -o launcher launcher.go

View File

@@ -2,14 +2,14 @@ rm -rf ../dist
mkdir -p ../dist/modules
mkdir ./utils
cp ../../../utils/go/bridge/bridge.go ./utils/bridge.go
docker rmi go-php-builder --force
docker build . -t go-php-builder
docker run go-php-builder
docker run go-php-builder /bin/cat /root/go/app/launcher > ../dist/launcher
docker run go-php-builder /bin/cat /root/go/app/php.ini > ../dist/php.ini
docker run go-php-builder /bin/cat /usr/lib64/libphp7-7.1.so > ../dist/libphp7-7.1.so
docker run go-php-builder /bin/cat /usr/lib64/php/modules/curl.so > ../dist/modules/curl.so
docker run go-php-builder /bin/cat /usr/lib64/php/modules/json.so > ../dist/modules/json.so
docker run go-php-builder /bin/cat /usr/lib64/php/modules/mbstring.so > ../dist/modules/mbstring.so
docker rmi now-php-docker-image --force
docker build . -t now-php-docker-image
docker run now-php-docker-image
docker run now-php-docker-image /bin/cat /root/go/app/launcher > ../dist/launcher
docker run now-php-docker-image /bin/cat /root/go/app/php.ini > ../dist/php.ini
docker run now-php-docker-image /bin/cat /usr/lib64/libphp7-7.1.so > ../dist/libphp7-7.1.so
docker run now-php-docker-image /bin/cat /usr/lib64/php/modules/curl.so > ../dist/modules/curl.so
docker run now-php-docker-image /bin/cat /usr/lib64/php/modules/json.so > ../dist/modules/json.so
docker run now-php-docker-image /bin/cat /usr/lib64/php/modules/mbstring.so > ../dist/modules/mbstring.so
chmod +x ../dist/launcher
rm -rf ./utils

View File

@@ -4,7 +4,9 @@ import (
now "./utils"
"bytes"
php "github.com/deuill/go-php"
"io/ioutil"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
@@ -20,23 +22,74 @@ func (h *PhpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
engine, _ := php.New()
context, _ := engine.NewContext()
var query = r.URL.Query()
getMap := make(map[string]string)
for k, v := range query {
for _, s := range v {
getMap[k] = s
for k, v := range r.URL.Query() {
if strings.HasSuffix(k, "[]") {
sb := ""
for _, s := range v {
if sb != "" {
sb += ","
}
sb += "'" + s + "'"
}
k = strings.TrimSuffix(k, "[]")
context.Eval("$_GET['" + k + "']=Array(" + sb + ");")
context.Eval("$_REQUEST['" + k + "']=Array(" + sb + ");")
} else {
s := v[len(v) - 1]
context.Eval("$_GET['" + k + "']='" + s + "';") // TODO escape quotes
context.Eval("$_REQUEST['" + k + "']='" + s + "';") // TODO escape quotes
}
}
context.Bind("_GET", getMap)
body, _ := ioutil.ReadAll(r.Body)
context.Eval("$HTTP_RAW_POST_DATA='" + string(body) + "';") // TODO escape-unescape
r.Body = ioutil.NopCloser(bytes.NewBuffer(body))
r.ParseForm()
postMap := make(map[string]string)
for k, v := range r.PostForm {
for _, s := range v {
postMap[k] = s
if strings.HasSuffix(k, "[]") {
sb := ""
for _, s := range v {
if sb != "" {
sb += ","
}
sb += "'" + s + "'"
}
k = strings.TrimSuffix(k, "[]")
context.Eval("$_POST['" + k + "']=Array(" + sb + ");")
context.Eval("$_REQUEST['" + k + "']=Array(" + sb + ");")
} else {
s := v[len(v) - 1]
context.Eval("$_POST['" + k + "']='" + s + "';") // TODO escape quotes
context.Eval("$_REQUEST['" + k + "']='" + s + "';") // TODO escape quotes
}
}
cookies := r.Cookies()
cookieMap := make(map[string]string)
for _, c := range cookies {
k, _ := url.QueryUnescape(c.Name)
v, _ := url.QueryUnescape(c.Value)
s := "'" + v + "'" // TODO escape quotes
if strings.HasSuffix(k, "[]") {
if value, exists := cookieMap[k]; exists {
cookieMap[k] = value + "," + s
} else {
cookieMap[k] = s
}
} else {
if _, exists := cookieMap[k]; !exists {
cookieMap[k] = s
}
}
}
for k, v := range cookieMap {
if strings.HasSuffix(k, "[]") {
k = strings.TrimSuffix(k, "[]")
context.Eval("$_COOKIE['" + k + "']=Array(" + v + ");")
} else {
context.Eval("$_COOKIE['" + k + "']=" + v + ";")
}
}
context.Bind("_POST", postMap)
envMap := make(map[string]string)
for _, e := range os.Environ() {
@@ -45,9 +98,20 @@ func (h *PhpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
context.Bind("_ENV", envMap)
context.Eval("$_SERVER[\"SERVER_NAME\"]=\"" + r.Host + "\";")
context.Eval("$_SERVER[\"SERVER_PORT\"]=\"443\";")
context.Eval("$_SERVER[\"HTTPS\"]=\"on\";")
for k, v := range r.Header {
for _, s := range v {
h := "HTTP_" + strings.ToUpper(strings.Replace(k, "-", "_", -1))
context.Eval("$_SERVER['" + h + "']='" + s + "';")
}
}
context.Eval("$_SERVER['SCRIPT_FILENAME']='" + h.ScriptFull + "';")
context.Eval("$_SERVER['REQUEST_METHOD']='" + r.Method + "';")
context.Eval("$_SERVER['REQUEST_URI']='" + r.URL.RequestURI() + "';") // TODO must be unescaped to align with php
context.Eval("$_SERVER['SERVER_PROTOCOL']='" + r.Proto + "';");
context.Eval("$_SERVER['SERVER_NAME']='" + r.Host + "';")
context.Eval("$_SERVER['SERVER_PORT']='443';")
context.Eval("$_SERVER['HTTPS']='on';")
context.Eval("http_response_code(200);")
var stdout bytes.Buffer
@@ -66,7 +130,6 @@ func (h *PhpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
w.Write(stdout.Bytes())
engine.Destroy()
}

View File

@@ -1,54 +1,17 @@
package main
import (
"bytes"
"fmt"
"net/http"
"os"
"path"
"path/filepath"
"strings"
php "github.com/deuill/go-php"
"bytes"
"fmt"
php "github.com/deuill/go-php"
)
var public = ""
func handler() {
engine, _ := php.New()
context, _ := engine.NewContext()
var bodyReader = strings.NewReader("Message=from test.go")
var httpReq, _ = http.NewRequest("POST", "/dummy/path", bodyReader)
httpReq.Header.Add("Content-Type", "application/x-www-form-urlencoded")
httpReq.ParseForm()
postMap := make(map[string]string)
for k, v := range httpReq.PostForm {
for _, s := range v {
postMap[k] = s
}
}
context.Bind("_POST", postMap)
var stdout bytes.Buffer
context.Output = &stdout
context.Exec(path.Join(public, "test.php"))
for k, v := range context.Header {
// see https://golang.org/src/net/http/header.go function writeSubset
for _, s := range v {
fmt.Printf("%s: %s\n", k, s)
}
}
fmt.Printf("\n")
fmt.Println(stdout.String())
engine.Destroy()
}
func main() {
ex, _ := os.Executable()
public = path.Join(filepath.Dir(ex), "public")
fmt.Printf("public %s\n", path.Join(filepath.Dir(ex), "public"))
handler()
engine, _ := php.New()
context, _ := engine.NewContext()
var stdout bytes.Buffer
context.Output = &stdout
context.Exec("test.php")
fmt.Println(stdout.String())
engine.Destroy()
}

View File

@@ -1,5 +1,2 @@
<?php
header('X-See-You: Tomorrow');
header('Content-Type: text/html; charset=UTF-8');
phpinfo();
?>
phpinfo();

View File

@@ -1,6 +1,6 @@
{
"name": "@now/php",
"version": "0.4.12",
"version": "0.4.13-canary.1",
"peerDependencies": {
"@now/build-utils": ">=0.0.1"
},

View File

@@ -1,3 +1,2 @@
<?php
print "cow:RANDOMNESS_PLACEHOLDER";
?>
print('cow:RANDOMNESS_PLACEHOLDER');

View File

@@ -1,3 +1,2 @@
<?php
print "yoda:RANDOMNESS_PLACEHOLDER";
?>
print('yoda:RANDOMNESS_PLACEHOLDER');

View File

@@ -1,3 +1,2 @@
<?php
print $_ENV["RANDOMNESS_ENV_VAR"] . ":env";
?>
print($_ENV['RANDOMNESS_ENV_VAR'] . ':env');

View File

@@ -0,0 +1,28 @@
<?php
header('Content-Type: text/plain');
print($_SERVER['SCRIPT_FILENAME'] . PHP_EOL);
print($_SERVER['REQUEST_METHOD'] . PHP_EOL);
print($_SERVER['REQUEST_URI'] . PHP_EOL);
print($_SERVER['HTTP_HOST'] . PHP_EOL);
print($_SERVER['HTTP_X_SOME_HEADER'] . PHP_EOL);
print($_SERVER['SERVER_PROTOCOL'] . PHP_EOL);
print($_SERVER['SERVER_NAME'] . PHP_EOL);
print($_SERVER['SERVER_PORT'] . PHP_EOL);
print($_SERVER['HTTPS'] . PHP_EOL);
print($_GET['get1'] . PHP_EOL);
var_dump($_GET['get2']);
print($_POST['post1'] . PHP_EOL);
var_dump($_POST['post2']);
print($_COOKIE['cookie1'] . PHP_EOL);
var_dump($_COOKIE['cookie2']);
print($_REQUEST['get1'] . PHP_EOL);
var_dump($_REQUEST['get2']);
print($_REQUEST['post1'] . PHP_EOL);
var_dump($_REQUEST['post2']);
print($_REQUEST['cookie1'] . PHP_EOL);
var_dump($_REQUEST['cookie2']);
print($HTTP_RAW_POST_DATA . PHP_EOL);
print('end' . PHP_EOL);

View File

@@ -0,0 +1,6 @@
{
"version": 2,
"builds": [
{ "src": "index.php", "use": "@now/php" }
]
}

View File

@@ -0,0 +1,152 @@
const assert = require('assert');
async function test1({ deploymentUrl, fetch }) {
const resp = await fetch(
`https://${deploymentUrl}/index.php?get1=foo&get1=bar&get2[]=bim&get2[]=bom`, {
headers: {
'X-Some-Header': 'x-some-header-value',
},
},
);
assert(resp.status === 200);
const text = await resp.text();
const lines = text.trim().split('\n');
assert.deepEqual(lines, [
'/var/task/user/index.php',
'GET',
'/index.php?get1=foo&get1=bar&get2%5B%5D=bim&get2%5B%5D=bom', // TODO fake news, must be unescaped
deploymentUrl, // example 'test-19phw91ph.now.sh'
'x-some-header-value',
'HTTP/1.1',
deploymentUrl, // example 'test-19phw91ph.now.sh'
'443',
'on',
'bar',
'array(2) {',
' [0]=>',
' string(3) "bim"',
' [1]=>',
' string(3) "bom"',
'}',
'',
'NULL',
'',
'NULL',
'bar',
'array(2) {',
' [0]=>',
' string(3) "bim"',
' [1]=>',
' string(3) "bom"',
'}',
'',
'NULL',
'',
'NULL',
'',
'end',
]);
}
async function test2({ deploymentUrl, fetch }) {
const resp = await fetch(
`https://${deploymentUrl}/index.php`, {
method: 'POST',
body: 'post1=baz&post1=bat&post2[]=pim&post2[]=pom',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
},
);
assert(resp.status === 200);
const text = await resp.text();
const lines = text.trim().split('\n');
assert.deepEqual(lines, [
'/var/task/user/index.php',
'POST',
'/index.php',
deploymentUrl, // example 'test-19phw91ph.now.sh'
'',
'HTTP/1.1',
deploymentUrl, // example 'test-19phw91ph.now.sh'
'443',
'on',
'',
'NULL',
'bat',
'array(2) {',
' [0]=>',
' string(3) "pim"',
' [1]=>',
' string(3) "pom"',
'}',
'',
'NULL',
'',
'NULL',
'bat',
'array(2) {',
' [0]=>',
' string(3) "pim"',
' [1]=>',
' string(3) "pom"',
'}',
'',
'NULL',
'post1=baz&post1=bat&post2[]=pim&post2[]=pom',
'end',
]);
}
async function test3({ deploymentUrl, fetch }) {
const resp = await fetch(
`https://${deploymentUrl}/index.php`, {
method: 'GET',
headers: {
Cookie: `cookie1=foo; cookie1=${escape('bar|bar')}; ${escape('cookie2[]')}=dim; ${escape('cookie2[]')}=${escape('dom|dom')}`,
},
},
);
assert(resp.status === 200);
const text = await resp.text();
const lines = text.trim().split('\n');
assert.deepEqual(lines, [
'/var/task/user/index.php',
'GET',
'/index.php',
deploymentUrl, // example 'test-19phw91ph.now.sh'
'',
'HTTP/1.1',
deploymentUrl, // example 'test-19phw91ph.now.sh'
'443',
'on',
'',
'NULL',
'',
'NULL',
'foo',
'array(2) {',
' [0]=>',
' string(3) "dim"',
' [1]=>',
' string(7) "dom|dom"',
'}',
'',
'NULL',
'',
'NULL',
'',
'NULL',
'',
'end',
]);
}
module.exports = async (opts) => {
await test1(opts);
await test2(opts);
await test3(opts);
};

View File

@@ -0,0 +1,5 @@
<?php
header('Content-Type: text/plain');
header('Content-Type: text/plain; charset=UTF-16');
setcookie('cookie1', 'cookie1value');
setcookie('cookie2', 'cookie2value');

View File

@@ -0,0 +1,6 @@
{
"version": 2,
"builds": [
{ "src": "index.php", "use": "@now/php" }
]
}

View File

@@ -0,0 +1,9 @@
const assert = require('assert');
module.exports = async ({ deploymentUrl, fetch }) => {
const resp = await fetch(`https://${deploymentUrl}/index.php`);
assert(resp.status === 200);
assert.equal(resp.headers.get('content-type'), 'text/plain; charset=UTF-16');
assert(resp.headers.get('set-cookie').includes('cookie1=cookie1value'));
assert(resp.headers.get('set-cookie').includes('cookie2=cookie2value'));
};

View File

@@ -0,0 +1,10 @@
<?php
// regression test for go-php engine reusage. on failure prints
// Fatal error: Cannot redeclare some_function() (previously declared in /var/task/user/index.php:7)
function some_function() {
print("paskantamasaari");
}
some_function();

View File

@@ -0,0 +1,6 @@
{
"version": 2,
"builds": [
{ "src": "index.php", "use": "@now/php" }
]
}

View File

@@ -0,0 +1,8 @@
const assert = require('assert');
module.exports = async ({ deploymentUrl, fetch }) => {
const resp1 = await fetch(`https://${deploymentUrl}/index.php`);
assert.equal(await resp1.text(), 'paskantamasaari');
const resp2 = await fetch(`https://${deploymentUrl}/index.php`);
assert.equal(await resp2.text(), 'paskantamasaari');
};

View File

@@ -0,0 +1,23 @@
const fetch = require('node-fetch');
const retryBailByDefault = require('./retry-bail-by-default.js');
async function fetchRetry (...args) {
return await retryBailByDefault(async (canRetry) => {
try {
return await fetch(...args);
} catch (error) {
if (error.code === 'ENOTFOUND') {
// getaddrinfo ENOTFOUND api.zeit.co like some transient dns issue
throw canRetry(error);
} else
if (error.code === 'ETIMEDOUT') {
// request to https://api-gru1.zeit.co/v3/now/deployments/dpl_FBWWhpQomjgwjJLu396snLrGZYCm failed, reason:
// connect ETIMEDOUT 18.228.143.224:443
throw canRetry(error);
}
throw error;
}
}, { factor: 1, retries: 3 });
}
module.exports = fetchRetry;

View File

@@ -1,8 +1,8 @@
const assert = require('assert');
const { createHash } = require('crypto');
const fetch = require('node-fetch');
const { homedir } = require('os');
const path = require('path');
const fetch = require('./fetch-retry.js');
async function nowDeploy (bodies, randomness) {
const files = Object.keys(bodies)
@@ -18,7 +18,7 @@ async function nowDeploy (bodies, randomness) {
const nowDeployPayload = {
version: 2,
env: { RANDOMNESS_ENV_VAR: randomness },
env: Object.assign({}, nowJson.env, { RANDOMNESS_ENV_VAR: randomness }),
build: { env: { RANDOMNESS_BUILD_ENV_VAR: randomness } },
name: 'test',
files,
@@ -27,12 +27,13 @@ async function nowDeploy (bodies, randomness) {
meta: {}
};
console.log(`posting ${files.length} files`);
for (const { file: filename } of files) {
const json = await filePost(
await filePost(
bodies[filename],
digestOfFile(bodies[filename])
);
if (json.error) throw new Error(json.error.message);
}
let deploymentId;
@@ -45,6 +46,8 @@ async function nowDeploy (bodies, randomness) {
deploymentUrl = json.url;
}
console.log('id', deploymentId);
for (let i = 0; i < 500; i += 1) {
const { state } = await deploymentGet(deploymentId);
if (state === 'ERROR') throw new Error(`State of ${deploymentUrl} is ${state}`);
@@ -76,8 +79,13 @@ async function filePost (body, digest) {
headers,
body
});
const json = await resp.json();
return await resp.json();
if (json.error) {
console.log('headers', resp.headers);
throw new Error(json.error.message);
}
return json;
}
async function deploymentPost (payload) {
@@ -86,7 +94,11 @@ async function deploymentPost (payload) {
body: JSON.stringify(payload)
});
const json = await resp.json();
if (json.error) throw new Error(json.error.message);
if (json.error) {
console.log('headers', resp.headers);
throw new Error(json.error.message);
}
return json;
}
@@ -96,33 +108,43 @@ async function deploymentGet (deploymentId) {
}
async function fetchWithAuth (url, opts = {}) {
const apiHost = process.env.API_HOST || 'api.zeit.co';
const urlWithHost = `https://${apiHost}${url}`;
if (!opts.headers) opts.headers = {};
let token;
if (process.env.NOW_AUTH_TOKENS) {
const tokens = process.env.NOW_AUTH_TOKENS.split(',');
if (process.env.CIRCLE_BUILD_NUM) {
token = tokens[Number(process.env.CIRCLE_BUILD_NUM) % tokens.length];
if (!opts.headers.Authorization) {
let token;
if (process.env.NOW_AUTH_TOKENS) {
const tokens = process.env.NOW_AUTH_TOKENS.split(',');
if (process.env.CIRCLE_BUILD_NUM) {
token = tokens[Number(process.env.CIRCLE_BUILD_NUM) % tokens.length];
} else {
token = tokens[Math.floor(Math.random() * tokens.length)];
}
} else {
token = tokens[Math.floor(Math.random() * tokens.length)];
const authJsonPath = path.join(homedir(), '.now/auth.json');
token = require(authJsonPath).token;
}
} else {
const authJsonPath = path.join(homedir(), '.now/auth.json');
token = require(authJsonPath).token;
opts.headers.Authorization = `Bearer ${token}`;
}
opts.headers.Authorization = `Bearer ${token}`;
return await fetchApiWithChecks(urlWithHost, opts);
return await fetchApi(url, opts);
}
async function fetchApiWithChecks (url, opts = {}) {
// const { method = 'GET', body } = opts;
// console.log('fetch', method, url);
// if (body) console.log(encodeURIComponent(body).slice(0, 80));
const resp = await fetch(url, opts);
return resp;
async function fetchApi (url, opts = {}) {
const apiHost = process.env.API_HOST || 'api.zeit.co';
const urlWithHost = `https://${apiHost}${url}`;
const { method = 'GET', body } = opts;
if (process.env.VERBOSE) {
console.log('fetch', method, url);
if (body) console.log(encodeURIComponent(body).slice(0, 80));
}
return await fetch(urlWithHost, opts);
}
module.exports = nowDeploy;
module.exports = {
fetchApi,
fetchWithAuth,
nowDeploy
};

View File

@@ -0,0 +1,23 @@
const retry = require('async-retry');
function canRetry (error) {
error.dontBail = true;
return error;
}
async function retryBailByDefault (fn, opts) {
return await retry(async () => {
try {
return await fn(canRetry);
} catch (error) {
if (error.dontBail) {
delete error.dontBail;
} else {
error.bail = true;
}
throw error;
}
}, opts);
}
module.exports = retryBailByDefault;

View File

@@ -1,11 +1,11 @@
const assert = require('assert');
const bufferReplace = require('buffer-replace');
const fetch = require('node-fetch');
const fs = require('fs-extra');
const glob = require('util').promisify(require('glob'));
const path = require('path');
const { spawn } = require('child_process');
const nowDeploy = require('./now-deploy.js');
const fetch = require('./fetch-retry.js');
const { nowDeploy } = require('./now-deploy.js');
async function packAndDeploy (builderPath) {
const tgzName = (await spawnAsync('npm', [ '--loglevel', 'warn', 'pack' ], {
@@ -66,10 +66,11 @@ async function testDeployment ({ builderUrl, buildUtilsUrl }, fixturePath) {
}
bodies['now.json'] = Buffer.from(JSON.stringify(nowJson));
delete bodies['probe.js'];
const { deploymentId, deploymentUrl } = await nowDeploy(bodies, randomness);
console.log('deploymentUrl', deploymentUrl);
for (const probe of nowJson.probes) {
for (const probe of nowJson.probes || []) {
console.log('testing', JSON.stringify(probe));
const probeUrl = `https://${deploymentUrl}${probe.path}`;
const text = await fetchDeploymentUrl(probeUrl, {
@@ -91,6 +92,11 @@ async function testDeployment ({ builderUrl, buildUtilsUrl }, fixturePath) {
}
}
const probeJsFullPath = path.resolve(fixturePath, 'probe.js');
if (await fs.exists(probeJsFullPath)) {
await require(probeJsFullPath)({ deploymentUrl, fetch });
}
return { deploymentId, deploymentUrl };
}

View File

@@ -216,7 +216,8 @@ describe('normalizePackageJson', () => {
next: 'canary',
},
scripts: {
'now-build': 'next build --lambdas',
'now-build':
'NODE_OPTIONS=--max_old_space_size=3000 next build --lambdas',
},
});
});
@@ -246,7 +247,8 @@ describe('normalizePackageJson', () => {
next: 'canary',
},
scripts: {
'now-build': 'next build --lambdas',
'now-build':
'NODE_OPTIONS=--max_old_space_size=3000 next build --lambdas',
},
});
});
@@ -270,7 +272,8 @@ describe('normalizePackageJson', () => {
next: 'canary',
},
scripts: {
'now-build': 'next build --lambdas',
'now-build':
'NODE_OPTIONS=--max_old_space_size=3000 next build --lambdas',
},
});
});
@@ -294,7 +297,8 @@ describe('normalizePackageJson', () => {
next: 'canary',
},
scripts: {
'now-build': 'next build --lambdas',
'now-build':
'NODE_OPTIONS=--max_old_space_size=3000 next build --lambdas',
},
});
});
@@ -318,7 +322,8 @@ describe('normalizePackageJson', () => {
next: 'canary',
},
scripts: {
'now-build': 'next build --lambdas',
'now-build':
'NODE_OPTIONS=--max_old_space_size=3000 next build --lambdas',
},
});
});
@@ -380,7 +385,8 @@ describe('normalizePackageJson', () => {
scripts: {
dev: 'next',
build: 'next build',
'now-build': 'next build --lambdas',
'now-build':
'NODE_OPTIONS=--max_old_space_size=3000 next build --lambdas',
start: 'next start',
test: "xo && stylelint './pages/**/*.js' && jest",
},

View File

@@ -21,10 +21,10 @@ type Request struct {
}
type Response struct {
StatusCode int `json:"statusCode"`
Headers map[string]string `json:"headers"`
Encoding string `json:"encoding,omitemtpy"`
Body string `json:"body"`
StatusCode int `json:"statusCode"`
Headers map[string][]string `json:"headers"`
Encoding string `json:"encoding,omitemtpy"`
Body string `json:"body"`
}
type ResponseWriter struct {
@@ -68,20 +68,17 @@ func Serve(handler http.Handler, req *Request) (res Response, err error) {
for k, v := range req.Headers {
r.Header.Add(k, v)
switch strings.ToLower(k) {
case "host":
r.Host = v
case "content-length":
contentLength, _ := strconv.ParseInt(v, 10, 64)
r.ContentLength = contentLength
case "x-forwarded-for":
case "x-real-ip":
r.RemoteAddr = v
}
if strings.ToLower(k) == "host" {
// we need to set `Host` in the request
// because Go likes to ignore the `Host` header
// see https://github.com/golang/go/issues/7682
r.Host = v
case "host":
// we need to set `Host` in the request
// because Go likes to ignore the `Host` header
// see https://github.com/golang/go/issues/7682
r.Host = v
case "content-length":
contentLength, _ := strconv.ParseInt(v, 10, 64)
r.ContentLength = contentLength
case "x-forwarded-for":
case "x-real-ip":
r.RemoteAddr = v
}
}
@@ -96,10 +93,10 @@ func Serve(handler http.Handler, req *Request) (res Response, err error) {
handler.ServeHTTP(w, r)
defer r.Body.Close()
headers := make(map[string]string)
headers := make(map[string][]string)
for k, v := range w.headers {
for _, s := range v {
headers[k] = s
headers[k] = append(headers[k], s)
}
}