Просмотр исходного кода

[TypeScript] Update Deno to 1.25.0 (#7563)

* Update Deno benchmark

* use official docker image

* use port 8080

* hostname
Divy Srivastava 2 лет назад
Родитель
Сommit
eb8b1c7b90

+ 6 - 3
frameworks/TypeScript/deno/README.md

@@ -1,11 +1,14 @@
 # [Deno](https://deno.land/) - A secure runtime for JavaScript and TypeScript
 
+Benchmark Author: Divy Srivastava [@littledivy](https://github.com/littledivy)
+
 ## Description
 
-Deno is a simple, modern and secure runtime for JavaScript and TypeScript that uses V8 and is built in Rust.
+Deno is a simple, modern and secure runtime for JavaScript and TypeScript that
+uses V8 and is built in Rust.
 
-* [Deno Manual](https://deno.land/manual)
-* [Deno Standard Library](https://deno.land/std)
+- [Deno Manual](https://deno.land/manual)
+- [Deno Standard Library](https://deno.land/std)
 
 ## Test URLs
 

+ 19 - 41
frameworks/TypeScript/deno/benchmark_config.json

@@ -1,42 +1,20 @@
 {
-    "framework": "deno",
-    "tests": [{
-        "default": {
-            "json_url": "/json",
-            "plaintext_url": "/plaintext",
-            "port": 8080,
-            "approach": "Realistic",
-            "classification": "Platform",
-            "language": "TypeScript",
-            "flavor": "deno",
-            "platform": "deno",
-            "webserver": "None",
-            "os": "Linux",
-            "database_os": "Linux",
-            "display_name": "deno",
-            "versus": "nodejs"
-        },
-        "mongodb-raw": {
-            "dockerfile": "deno.mongoraw.dockerfile",
-            "json_url": "/json",
-            "plaintext_url": "/plaintext",
-            "db_url": "/db",
-            "query_url": "/queries?queries=",
-            "update_url": "/updates?queries=",
-            "fortune_url": "/fortunes",
-            "port": 8080,
-            "approach": "Realistic",
-            "classification": "Platform",
-            "database": "MongoDB",
-            "orm": "Raw",
-            "language": "TypeScript",
-            "flavor": "deno",
-            "platform": "deno",
-            "webserver": "None",
-            "os": "Linux",
-            "database_os": "Linux",
-            "display_name": "deno",
-            "versus": "nodejs"
-        }
-    }]
-}
+  "framework": "deno",
+  "tests": [{
+    "default": {
+      "json_url": "/json",
+      "plaintext_url": "/plaintext",
+      "port": 8080,
+      "approach": "Realistic",
+      "classification": "Platform",
+      "language": "TypeScript",
+      "flavor": "deno",
+      "platform": "deno",
+      "webserver": "None",
+      "os": "Linux",
+      "database_os": "Linux",
+      "display_name": "deno",
+      "versus": "nodejs"
+    }
+  }]
+}

+ 1 - 23
frameworks/TypeScript/deno/config.toml

@@ -4,34 +4,12 @@ name = "deno"
 [main]
 urls.plaintext = "/plaintext"
 urls.json = "/json"
-urls.db = "/db"
-urls.query = "/query?queries="
-urls.update = "/update?queries="
-urls.fortune = "/fortunes"
 approach = "Realistic"
 classification = "Platform"
 database_os = "Linux"
-database = "MongoDB"
+database = "None"
 os = "Linux"
 orm = "Raw"
 platform = "deno"
 webserver = "None"
 versus = "nodejs"
-
-[mongodb]
-urls.plaintext = "/plaintext"
-urls.json = "/json"
-urls.db = "/db"
-urls.query = "/queries?queries="
-urls.update = "/updates?queries="
-urls.fortune = "/fortunes"
-urls.cached_query = "/cached?queries="
-approach = "Realistic"
-classification = "Platform"
-database = "MongoDB"
-database_os = "Linux"
-os = "Linux"
-orm = "Raw"
-platform = "nodejs"
-webserver = "None"
-versus = "nodejs"

+ 2 - 3
frameworks/TypeScript/deno/deno.dockerfile

@@ -1,11 +1,10 @@
-FROM hayd/alpine-deno:latest
+FROM denoland/deno:1.25.0
 
 EXPOSE 8080
 
 WORKDIR /app
 
 USER deno
-ENV DATABASE mongodb
 
 COPY ./src .
 
@@ -13,4 +12,4 @@ RUN deno cache main.ts
 
 EXPOSE 8080
 
-CMD ["run", "--allow-net", "main.ts"]
+CMD ["run", "--allow-net", "--unstable", "main.ts"]

+ 0 - 18
frameworks/TypeScript/deno/deno.mongoraw.dockerfile

@@ -1,18 +0,0 @@
-FROM hayd/alpine-deno:latest
-
-
-EXPOSE 8080
-
-WORKDIR /app
-
-USER deno
-ENV DATABASE mongodb
-
-COPY ./src .
-
-RUN deno cache main.mongoraw.ts
-
-EXPOSE 8080
-
-CMD ["run", "--allow-net", "main.mongoraw.ts"]
-

+ 0 - 16
frameworks/TypeScript/deno/src/_handlers/json.ts

@@ -1,16 +0,0 @@
-import { ServerRequest, SERVER, dyn_date, MIME_JSON } from "../depends.ts";
-
-export const headers = new Headers([
-  ["server", SERVER],
-  ["content-type", MIME_JSON],
-]);
-
-export default async (req: ServerRequest): Promise<void> => {
-  const HELLO_OBJ = { message: "Hello, World!" };
-  headers.set("date", dyn_date());
-  req.respond({
-    headers,
-    body: JSON.stringify(HELLO_OBJ),
-  });
-  return;
-};

+ 0 - 111
frameworks/TypeScript/deno/src/_handlers/mongodb-raw/database.ts

@@ -1,111 +0,0 @@
-import { MongoClient } from "../../depends.ts";
-
-const mongoUrl = "mongodb://tfb-database:27017";
-const dbName = "hello_world";
-
-export const client: MongoClient = new MongoClient();
-await client.connect(mongoUrl);
-export let World = client.database(dbName).collection("world");
-export let Fortune = client.database(dbName).collection("fortune");
-
-export const randomNumber = (): number => Math.floor(Math.random() * 10000) + 1;
-
-export const fillArrayWithFn = async<T = any>(v: Function, l: number) => {
-  let o = [];
-  for (let i = 0; i < l; i += 1) o.push(await v());
-  return o;
-};
-
-export interface FortuneData {
-  id: number;
-  message: string;
-  _id?: unknown;
-}
-export const htmlEncodeByRegExp = (str: string) => {
-  let s = "";
-  if (str.length == 0) return "";
-  s = str.replaceAll(/&/g, "&amp;");
-  s = s.replaceAll(/</g, "&lt;");
-  s = s.replaceAll(/>/g, "&gt;");
-  // s = s.replaceAll(/ /g, "&nbsp;");
-  s = s.replaceAll(/\'/g, "'");
-  s = s.replaceAll(/\"/g, '"');
-  return s;
-};
-export const _fortunes_head = [
-  "<!DOCTYPE html>",
-  "<html>",
-  "<head><title>Fortunes</title></head>",
-  "<body>",
-  "<table>",
-  "<tr>",
-  "<th>id</th>",
-  "<th>message</th>",
-  "</tr>",
-].join("");
-export const _fortunes_end = ["</table>", "</body>", "</html>"].join("");
-export const _fortunes_com = ["<tr>", "</tr>", "<td>", "</td>"];
-export const generateFortunes = (input: FortuneData[]) => {
-  let f = input
-    .map((v) =>
-      [
-        _fortunes_com[0],
-        _fortunes_com[2],
-        v.id.toString(),
-        _fortunes_com[3],
-        _fortunes_com[2],
-        htmlEncodeByRegExp(v.message),
-        _fortunes_com[3],
-        _fortunes_com[1],
-      ].join("")
-    )
-    .join("");
-
-  return _fortunes_head + f + _fortunes_end;
-};
-
-export const randomWorld = async () => {
-  let world = (await World.findOne({
-    id: randomNumber(),
-  })) as FortuneData;
-  world._id = undefined;
-  return world;
-};
-
-export const getAllFortunes = async () => {
-  return await Fortune.find().toArray();
-};
-
-export const updateQuery = async () => {
-  const one = (await World.findOne({
-    id: randomNumber(),
-  })) as any;
-  one.randomNumber = randomNumber();
-  await World.updateOne(
-    {
-      id: one.id,
-    },
-    one
-  );
-  return {
-    id: one.id,
-    randomNumber: one.randomNumber,
-  };
-};
-
-export const additionalFortune = {
-  id: 0,
-  message: "Additional fortune added at request time.",
-};
-
-export const resolveQueryNumber = (s: string) => {
-  let r: number;
-  if (/^\d+$/.test(s)) {
-    r = Number(s);
-    if (r > 500) r = 500;
-    if (r < 1) r = 1;
-  } else {
-    r = 1;
-  }
-  return r;
-};

+ 0 - 23
frameworks/TypeScript/deno/src/_handlers/mongodb-raw/fortunes.ts

@@ -1,23 +0,0 @@
-import { ServerRequest, SERVER, dyn_date, MIME_HTML } from "../../depends.ts";
-import {
-  getAllFortunes,
-  additionalFortune,
-  generateFortunes,
-  FortuneData,
-} from "./database.ts";
-
-export const headers = new Headers([
-  ["server", SERVER],
-  ["content-type", MIME_HTML],
-]);
-
-export default async (req: ServerRequest): Promise<void> => {
-  let fortunes = await getAllFortunes();
-  fortunes.push(additionalFortune);
-  fortunes.sort((a: any, b: any) => a.message.localeCompare(b.message));
-  headers.set("date", dyn_date());
-  req.respond({
-    headers,
-    body: generateFortunes(fortunes as FortuneData[]),
-  });
-};

+ 0 - 12
frameworks/TypeScript/deno/src/_handlers/mongodb-raw/handlers.ts

@@ -1,12 +0,0 @@
-import { Handlers } from "./../../handlers.ts";
-import FortunesHandler from "./fortunes.ts";
-import MultipleQueriesHandler from "./multiple-queries.ts";
-import SingleQueryHandler from "./single-query.ts";
-import UpdatesHandler from "./updates.ts";
-
-export const MongoRawHandlers = {
-  "/db": SingleQueryHandler,
-  "/queries": MultipleQueriesHandler,
-  "/updates": UpdatesHandler,
-  "/fortunes": FortunesHandler,
-} as Handlers;

+ 0 - 18
frameworks/TypeScript/deno/src/_handlers/mongodb-raw/multiple-queries.ts

@@ -1,18 +0,0 @@
-import { ServerRequest, SERVER, dyn_date, MIME_JSON } from "../../depends.ts";
-import { randomWorld, fillArrayWithFn, resolveQueryNumber } from "./database.ts";
-
-export const headers = new Headers([
-  ["server", SERVER],
-  ["content-type", MIME_JSON],
-]);
-
-export default async (req: ServerRequest): Promise<void> => {
-  const u = new URL(req.url, "http://deno");
-  const l = resolveQueryNumber(u.searchParams.get("queries") ?? "1");
-  const rnd = await Promise.all(await fillArrayWithFn(() => randomWorld(), l));
-  headers.set("date", dyn_date());
-  req.respond({
-    headers,
-    body: JSON.stringify(rnd),
-  });
-};

+ 0 - 16
frameworks/TypeScript/deno/src/_handlers/mongodb-raw/single-query.ts

@@ -1,16 +0,0 @@
-import { ServerRequest, SERVER, dyn_date, MIME_JSON } from "../../depends.ts";
-import { randomWorld } from "./database.ts";
-
-export const headers = new Headers([
-  ["server", SERVER],
-  ["content-type", MIME_JSON],
-]);
-
-export default async (req: ServerRequest): Promise<void> => {
-  const rnd = await randomWorld();
-  headers.set("date", dyn_date());
-  req.respond({
-    headers,
-    body: JSON.stringify(rnd),
-  });
-};

+ 0 - 18
frameworks/TypeScript/deno/src/_handlers/mongodb-raw/updates.ts

@@ -1,18 +0,0 @@
-import { ServerRequest, SERVER, dyn_date, MIME_JSON } from "../../depends.ts";
-import { updateQuery, fillArrayWithFn, resolveQueryNumber } from "./database.ts";
-
-export const headers = new Headers([
-  ["server", SERVER],
-  ["content-type", MIME_JSON],
-]);
-
-export default async (req: ServerRequest): Promise<void> => {
-  const u = new URL(req.url, "http://deno");
-  const l = resolveQueryNumber(u.searchParams.get("queries") ?? "1");
-  const rnd = await Promise.all(await fillArrayWithFn(() => updateQuery(), l));
-  headers.set("date", dyn_date());
-  req.respond({
-    headers,
-    body: JSON.stringify(rnd),
-  });
-};

+ 0 - 17
frameworks/TypeScript/deno/src/_handlers/plaintext.ts

@@ -1,17 +0,0 @@
-import {
-  ServerRequest,
-  SERVER,
-  dyn_date,
-  MIME_TEXT,
-  HELLO_WORLD,
-} from "../depends.ts";
-
-const headers = new Headers([
-  ["server", SERVER],
-  ["content-type", MIME_TEXT],
-]);
-
-export default async (req: ServerRequest): Promise<void> => {
-  headers.set("date", dyn_date());
-  req.respond({ headers, body: HELLO_WORLD });
-};

+ 0 - 23
frameworks/TypeScript/deno/src/depends.ts

@@ -1,23 +0,0 @@
-export type { Response } from "https://deno.land/[email protected]/http/server.ts";
-
-export {
-  ServerRequest,
-  serve,
-} from "https://deno.land/[email protected]/http/server.ts";
-
-export { MongoClient, Bson } from "https://deno.land/x/[email protected]/mod.ts";
-
-export const SERVER: string = "Deno";
-
-let date = new Date().toUTCString();
-setInterval(() => (date = new Date().toUTCString()), 850);
-export const dyn_date = () => date;
-
-export const MIME_JSON = "application/json";
-export const MIME_HTML = "text/html; charset=utf-8";
-
-export const HELLO_WORLD: Uint8Array = new TextEncoder().encode(
-  "Hello, World!"
-);
-
-export const MIME_TEXT = "text/plain; charset=UTF-8";

+ 0 - 17
frameworks/TypeScript/deno/src/handlers.ts

@@ -1,17 +0,0 @@
-import type { ServerRequest } from "./depends.ts";
-import JSONHandler from "./_handlers/json.ts";
-import PlaintextHandler from "./_handlers/plaintext.ts";
-
-export interface Handler {
-  (request: ServerRequest): Promise<void>;
-}
-
-export interface Handlers {
-  [index: string]: Handler;
-}
-
-export default {
-  "/json": JSONHandler,
-  "/plaintext": PlaintextHandler,
-} as Handlers;
-

+ 0 - 22
frameworks/TypeScript/deno/src/main.mongoraw.ts

@@ -1,22 +0,0 @@
-import { serve } from "https://deno.land/[email protected]/http/server.ts";
-import DefaultHandlers from "./handlers.ts";
-import { MongoRawHandlers } from "./_handlers/mongodb-raw/handlers.ts";
-const handlers = {
-  ...DefaultHandlers,
-  ...MongoRawHandlers,
-};
-
-for await (const req of serve("0.0.0.0:8080")) {
-  const url = new URL(req.url, "http://deno");
-  if (handlers[url.pathname] != undefined) {
-    handlers[url.pathname](req as any).catch((e) => {
-      console.error(e);
-      Deno.exit(9);
-    });
-  } else {
-    req.respond({
-      body: "404 Not Found",
-    });
-  }
-  continue;
-}

+ 29 - 15
frameworks/TypeScript/deno/src/main.ts

@@ -1,15 +1,29 @@
-import { serve } from "https://deno.land/[email protected]/http/server.ts";
-import Handlers from "./handlers.ts";
-for await (const req of serve("0.0.0.0:8080")) {
-  if (Handlers[req.url] != undefined) {
-    Handlers[req.url](req as any).catch((e) => {
-      console.error(e);
-      Deno.exit(9);
-    });
-  } else {
-    req.respond({
-      body: "404 Not Found",
-    });
-  }
-  continue;
-}
+const options = {
+  // Date and Content-Type headers are automatically set.
+  headers: {
+    "Server": "Deno",
+  },
+};
+
+type HandlerFn = (req: Request) => Promise<Response> | Response;
+
+const handlers: Record<string, HandlerFn> = {
+  "/json": () => Response.json({ message: "Hello, World!" }, options),
+  "/plaintext": () => new Response("Hello, World!", options),
+};
+
+Deno.serve({
+  handler: (req: Request) => {
+    const path = req.url.slice(req.url.indexOf("/", 8));
+    const fn = handlers[path];
+    return fn
+      ? fn(req)
+      : new Response("404 Not Found", { status: 404, ...options });
+  },
+  onError(err) {
+    console.error(err);
+    Deno.exit(9);
+  },
+  port: 8080,
+  hostname: "0.0.0.0",
+});

+ 0 - 70
frameworks/TypeScript/deno/src/tsconfig.json

@@ -1,70 +0,0 @@
-{
-  "compilerOptions": {
-    /* Visit https://aka.ms/tsconfig.json to read more about this file */
-
-    /* Basic Options */
-    // "incremental": true,                   /* Enable incremental compilation */
-    "target": "esnext",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
-    "module": "esnext",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
-    // "lib": [],                             /* Specify library files to be included in the compilation. */
-    // "allowJs": true,                       /* Allow javascript files to be compiled. */
-    // "checkJs": true,                       /* Report errors in .js files. */
-    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
-    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
-    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
-    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
-    // "outFile": "./",                       /* Concatenate and emit output to single file. */
-    // "outDir": "./",                        /* Redirect output structure to the directory. */
-    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
-    // "composite": true,                     /* Enable project compilation */
-    // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */
-    // "removeComments": true,                /* Do not emit comments to output. */
-    // "noEmit": true,                        /* Do not emit outputs. */
-    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
-    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
-    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
-
-    /* Strict Type-Checking Options */
-    "strict": false,                           /* Enable all strict type-checking options. */
-    "noImplicitAny": false,                 /* Raise error on expressions and declarations with an implied 'any' type. */
-    // "strictNullChecks": true,              /* Enable strict null checks. */
-    "strictFunctionTypes": false,           /* Enable strict checking of function types. */
-    // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
-    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
-    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
-    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */
-
-    /* Additional Checks */
-    // "noUnusedLocals": true,                /* Report errors on unused locals. */
-    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
-    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
-    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */
-    // "noUncheckedIndexedAccess": true,      /* Include 'undefined' in index signature results */
-
-    /* Module Resolution Options */
-    // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
-    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
-    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
-    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
-    // "typeRoots": [],                       /* List of folders to include type definitions from. */
-    // "types": [],                           /* Type declaration files to be included in compilation. */
-    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
-    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
-    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
-    // "allowUmdGlobalAccess": true,          /* Allow accessing UMD globals from modules. */
-
-    /* Source Map Options */
-    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
-    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
-    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
-    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
-
-    /* Experimental Options */
-    "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
-    "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
-
-    /* Advanced Options */
-    "skipLibCheck": true,                     /* Skip type checking of declaration files. */
-    "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
-  }
-}