Skip to content

Review for YourCodeReview (ru) - #1

Open
AlexMcArrow wants to merge 4 commits into
masterfrom
0.3.x
Open

Review for YourCodeReview (ru)#1
AlexMcArrow wants to merge 4 commits into
masterfrom
0.3.x

Conversation

@AlexMcArrow

@AlexMcArrow AlexMcArrow commented Nov 3, 2021

Copy link
Copy Markdown
Owner

Основные изменения:

  • Переход на модульную архитектуру

Вопросы:

  • Архитектура

    На текущий момент есть\будет 4 (четыре) блока модулей:

    • RPC - модули внешней двунаправленной связи (чтение\запись), для реализации: получение данных из сервиса (пассивный режим), управление сервисом
    • Metric - модуль система сбора значений
    • Logger - модуль логирования Metric при выходе контролируемых значений из допустимых диапазонов
    • Caller - модуль исходящих данных (активный режим) - чем-то схож с Logger только пишет локально в файл (в момент написания данного текста пришло понимание что Logger следует сделать "драйверов" Caller, т.к. фактически исполняется одна логика)

    Перечень и параметры модулей описываются в config.json (подразумевается последующая возможность вносить правки в блок-конфигурации по средствам RPC с последующим обновлением файла config.json на диске

    Интересны ваши мысли, идеи, замечания по архитектуре, системе модульности и что угодно

  • Механизм передачи контроля дочерним модулям src/server.js#146-210 link

    $$pipe - реализован для изолированного доступа "модулей" только к разрешенным методам.

    Какие есть другие варианты?

Игнорировать:

  • src/ext/dns.js - временно закомментирован для последующей адаптации
  • вызов console.log - используется для логирования всего и вся на этапе разработки

@YourCodeReview

Copy link
Copy Markdown

Переход на модульную архитектуру
Интересно получить общие замечания по коду и советы

  1. Мнение о вводимой архитектуре и предложения по улучшению
  2. Реализован механизм передачи управления основным кодом дочерним модулям - корректность текущей и другие варианты реализации

Comment thread cli/index.js
}

/** Read args from cmd */
var args = Parse(process.argv);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Возможно, для парсинга аргументов имеет смысл воспользоваться готовыми библиотеками, на подобие minimist

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Стараюсь не использовать внешние библиотеки или включать их технические решения в свой код.
Функция Parse взята из одной библиотеки по разбору аргументов - думаю стоит указать автора

Comment thread cli/index.js
req.write(requestJSON);
req.end();
};
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Код, связанный с отправкой и обработкой запроса можно несколько сократить при использовании сторонней библиотеки axios или https://www.npmjs.com/package/node-fetch .

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Стараюсь не использовать внешние библиотеки или включать их технические решения в свой код

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно узнать, почему?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Есть несколько моментов:

  1. большой размер зависимостей и их зависимостей, что увеличивает размер билда
  2. при формировании билда (использую webpack для формирования единого JS-файла) поподает очень много "мусора" (т.е. реально не используемого кода на который ссылаются реализации)
  3. если не использовать билды - проблема развертывания в изолированных пром. средах
  4. желание иметь только реально задействованный код (пример: если подтянуть lodash для использования 2-3 методов, в билд упаковывается почти весь lodash)

Comment thread cli/index.js
console.log('\t--method\t*\texecuted method')
console.log('')
return
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Библиотека commander.js предоставляет удобный интерфейс для вывода подобного рода сообщений (да и предоставляет больше возможностей для работы с командной строкой, чем упоминаемый ранее minimist )

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Стараюсь не использовать внешние библиотеки или включать их технические решения в свой код.
Однако спасибо за подсказки в части предлагаемых библиотек

Comment thread src/ext/dns.js
@@ -0,0 +1,41 @@
// /**

@lis-dev lis-dev Nov 4, 2021

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Видимо, файлы src/ext/_all.js и src/ext/dns.js не нужны.

@AlexMcArrow AlexMcArrow Nov 4, 2021

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Данный файл временно закомментирован (что бы не мешался в процессе билда), но в последующем будем адаптирован

Comment thread src/modules/caller.js
@@ -0,0 +1,29 @@
const caller_drivers = require('./caller/_all')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Изменился код стайл, раньше использовался camesCase

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

В следующей итерации приведу стилистику кода в порядок

Comment thread src/modules/caller.js
@@ -0,0 +1,29 @@
const caller_drivers = require('./caller/_all')

class CALLER {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Изменился код стайл, раньше для классов использовался PascalCase

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

В следующей итерации приведу стилистику кода в порядок

Comment thread src/modules/caller.js
return true
}
return false
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

В конструкторе не имеет смысла возвращать boolean, он всё равно вернёт инстанс

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Большое спасибо, учту данный аспект


default:
return false
break

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

break лишний

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

На уровне исполнения кода - да. Однако оставил для соблюдения общей конструкции switch

Comment thread src/modules/caller.js
* @param {float} value
*/
ring(metric, level, value) {
this.$driver.ring(metric, level, value)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

$driver может быть undefined, стоит учесть или здесь или в конструкторе

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

При создании инстанса класса будет проверятся заполненность $driver и инстанс будет исключаться из пула как не инициализированный.
Подобное поведение можно увидеть в загрузчике RPCs

Comment thread src/modules/rpc/json.js
*/
start() {
console.log('RPC', 'JSON', 'start', this.$dsn)
if (this.$active) {

@lis-dev lis-dev Nov 4, 2021

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно уменьшить вложенность

if (!this.$active) {
  console.log('RPC', 'JSON', 'is disabled')
  return
}
...

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Большое спасибо, не обратил внимания

Comment thread src/modules/rpc/json.js
if (options.methods) {
assert(typeof options.methods === 'object' && !Array.isArray(options.methods), 'methods must be an object')
const keys = Object.keys(options.methods)
for (let n = 0; n < keys.length; n += 1) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

for (let key of keys)

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Comment thread src/modules/rpc/json.js
* Class representing a HTTP JSON-RPC server
* @see https://github.com/sangaman/http-jsonrpc-server
*/
class RpcServer {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Лучше вынести в отдельный файл

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

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

Comment thread src/modules/rpc/json.js
this.applyOptions(options)
}

this.server = http.createServer(reqHandler.bind(this))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

reqHandler используется только внутри класса, лучше его и сделать методом класса. Остальные функции ниже - тоже

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Comment thread src/modules/rpc/json.js
jsonrpc: '2.0',
}

if (request.id) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Валидацию (вместе с кодами ошибок) лучше вынести в отдельный класс

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

@lis-dev

lis-dev commented Nov 4, 2021

Copy link
Copy Markdown

Общие советы по коду:

  • перейти на современные методы работы с js (es6 и выше), использование import, await/async, классы и т.д.
  • использовать сторонние библиотеки
  • придерживаться единого код стайла
  • разбивать код по зонам ответственности

Comment thread cli/index.js
method: 'POST'
}

var buffer = '';

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Стоит переходить на современные стандарты и использовать let/const

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Хорошее замечание, спасибо

Comment thread cli/index.js
console.log('\t--p.[key]\t\tset params key \t"{}"')
console.log('\t--method\t*\texecuted method')
console.log('')
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

; в конце выражений в одних файлах есть везде (местами пропущены), в других их нет совсем.
В пределах проекта стоит придерживаться одного стиля кода

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Спасибо, буду внимательнее

Comment thread src/server.js
}

$readConfig(path) {
if (fs.existsSync(path)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Если сделать обратную проверку и выйти из функции - вложенность станет меньше

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Спасибо, не досмотрел

Comment thread src/server.js
try {
this.$config = JSON.parse(fs.readFileSync(path))
} catch (error) {
throw new Error(error.toString())

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

а в чем смысл ловить исключение и прокидывать его дальше без дополнительной логики?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

В текущей реализации - логики нет 😄
Уже есть понимание вынести обработку конфигурации в модуль что бы можно было использовать разных поставщиков данных (файлы, БД, и другие хранилища)

Comment thread src/server.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants