Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions fixup.sh
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
#!/bin/sh

cat >build/cjs/package.json <<!EOF
{
"type": "commonjs"
}
!EOF
package_version=`npm show . version`

cat >build/esm/package.json <<!EOF
for target in esm cjs; do
cp -R certs build/$target/src/
[[ $target == "esm" ]] && type="module" || type="commonjs"
cat >build/$target/package.json <<!EOF
{
"type": "module"
"version": "$package_version",
"type": "$type"
}
!EOF
done
11 changes: 5 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,16 @@
"name": "ydb-sdk",
"version": "3.4.0",
"description": "Node.js bindings for working with YDB API over gRPC",
"main": "build/cjs/index.js",
"module": "build/esm/index.js",
"main": "build/cjs/src/index.js",
"module": "build/esm/src/index.js",
"exports": {
".": {
"import": "./build/esm/index.js",
"require": "./build/cjs/index.js"
"import": "./build/esm/src/index.js",
"require": "./build/cjs/src/index.js"
}
},
"files": [
"build/**",
"certs/"
"build/**"
],
"scripts": {
"test:unit": "exit 0",
Expand Down
28 changes: 21 additions & 7 deletions src/ssl-credentials.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,30 @@
// noinspection ES6PreferShortImport
import {Logger} from './logging';
import { Logger } from './logging';
import fs from 'fs';
import path from 'path';
import {getRelTopLevelPath} from "./version";

const FALLBACK_INTERNAL_ROOT_CERTS = path.join(__dirname, getRelTopLevelPath(), 'certs/internal.pem');
const FALLBACK_SYSTEM_ROOT_CERTS = path.join(__dirname, getRelTopLevelPath(), 'certs/system.pem');
const CERTIFICATES_FOLDER = 'certs'
const RELATIVE_PATH = process.env.TEST_ENVIRONMENT ? '../' : './'
const RESOLVED_PATH = path.join(__dirname, RELATIVE_PATH, CERTIFICATES_FOLDER)
const FALLBACK_INTERNAL_ROOT_CERTS = path.join(RESOLVED_PATH, 'internal.pem');
const FALLBACK_SYSTEM_ROOT_CERTS = path.join(RESOLVED_PATH, 'system.pem');
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Почему бы содержимое сертификатов не положить в текстовом виде в переменную в какой-нибудь js модуль и не реквайрить их как обычно? Кажется это решит все проблемы (в том числе с бандлерами).

Copy link
Collaborator

@DavyJohnes DavyJohnes Sep 5, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

// certs.js

module.exports = {
  internal: '<text_contenxt_of_cert>',
  fallback: '<text_contenxt_of_cert>'
}

Copy link
Author

@esseswann esseswann Sep 5, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я вполне с этим согласен -- это предлагалось, однако по уму их надо бандлить вебпком во время компиляции из файлов\по урлу. Если есть консенсус по этому вопросу могу реализовать как через бандлер, так и переменной в .js

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А расскажите, в какой ситуации здесь появляются бандлеры? Ведь ydb-nodejs-sdk - это нодовая библиотека и, кажется, нет особого смысла бандлить/минифицировать код, который выполняется на ноде и не доезжает до клиента.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Смысл еще как есть. Кроме того, что код собирается в один файлик (что при прочих равных удобно) так еще и размер артефакта значительно меньше (учитывая что все node_modules не надо тащить). В контексте serverless функции очень значимый момент.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Хотелось бы понять можно ли всё-таки добавить webpack\esbuild для бандлинга cert или вставить сертификаты руками в код как предлагал @DavyJohnes

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я правильно понимаю, что бандлер и зависимости ydb-sdk тоже в бандл положит?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Да, он соберёт всё в один файл
Я тут посмотрел на размер system.pem, он довольно здоровый, поэтому я бы рекомендовал рассмотреть возможность скачивания его с публичного хранилища


function makeInternalRootCertificates() {
const internalRootCertificates = fs.readFileSync(FALLBACK_INTERNAL_ROOT_CERTS);
if (!fs.existsSync(FALLBACK_INTERNAL_ROOT_CERTS)
|| !fs.existsSync(FALLBACK_SYSTEM_ROOT_CERTS)) {
throw new Error(certificateNotFoundMessage)
}

const internalRootCertificates = fs.readFileSync(FALLBACK_INTERNAL_ROOT_CERTS)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@esseswann @tsufiev а почему решили оставить чтение с fs? Это тоже потребует дополнительной настройки бандлера. Может таки положим в виде строки в js модуль?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я не против, но меня немного смущает размер system.pem, возможно стоит обдумать как это можно сделать конфигурируемо

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Так а какая разница? Он тут так или иначе в памяти окажется, читаешь ты его с fs или реквайришь как js модуль.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Там есть кейс при котором его чтение необязательно, следовательно мы просто разжираем размер бандла. Это правда не меняет ситуацию относительно текущей, но теоретически можно было бы этого избежать

const fallbackSystemRootCertificates = fs.readFileSync(FALLBACK_SYSTEM_ROOT_CERTS)

let systemRootCertificates;
let systemRootCertificates: Buffer;
const tls = require('tls');
const nodeRootCertificates = tls.rootCertificates as string[] | undefined;
if (nodeRootCertificates && nodeRootCertificates.length > 0) {
systemRootCertificates = Buffer.from(nodeRootCertificates.join('\n'));
} else {
systemRootCertificates = fs.readFileSync(FALLBACK_SYSTEM_ROOT_CERTS);
systemRootCertificates = fallbackSystemRootCertificates;
}

return Buffer.concat([internalRootCertificates, systemRootCertificates]);
Expand Down Expand Up @@ -47,6 +55,12 @@ export function makeSslCredentials(endpoint: string, logger: Logger, sslCredenti
return makeDefaultSslCredentials();
}

const certificateNotFoundMessage = `No certificate found
It seems that you are using grpcs (secure) endpoint in a bundled environment.
Either provide YDB_SSL_ROOT_CERTIFICATES_FILE environment variable
or copy contents of ydb-nodejs-sdk/certs to ./certs path relative to the bundled file
`

export interface ISslCredentials {
rootCertificates?: Buffer,
clientPrivateKey?: Buffer,
Expand Down
8 changes: 1 addition & 7 deletions src/version.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,4 @@
import path from 'path';

export function getRelTopLevelPath() {
return process.env.TEST_ENVIRONMENT === 'dev' ? '..' : '../..';
}

const pkgInfo = require(path.join(getRelTopLevelPath(), 'package.json'));
import pkgInfo from "./../package.json";

function getVersion() {
return pkgInfo.version;
Expand Down
3 changes: 2 additions & 1 deletion tsconfig-base.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
"skipLibCheck": true,
"experimentalDecorators": true,
"allowJs": true,
"declaration": true
"declaration": true,
"resolveJsonModule": true
},
"include": [
"src/**/*.ts"
Expand Down