Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stage 1, Андрей Чешев, Политех #16

Merged
merged 18 commits into from
Feb 29, 2024

Conversation

Queenore
Copy link
Contributor

No description provided.

@Queenore Queenore changed the title stage 1, Чешев, Политех Stage 1, Чешев, Политех Feb 19, 2024
@Queenore Queenore changed the title Stage 1, Чешев, Политех Stage 1, Андрей Чешев, Политех Feb 19, 2024
@Queenore
Copy link
Contributor Author

Queenore commented Feb 19, 2024

Отчет

Copy link
Member

@lamtev lamtev left a comment

Choose a reason for hiding this comment

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

В решении есть серьёзные недочёты, такие как отсутствие обработки исключений и некорректная остановка сервиса. И, похоже, профилировалось приложение с "холодной" jvm (прошу учесть в следующих этапах)

Тем не менее, судя по отчёту, по результатам профилирования первого решения были выполнены оптимизации, направленные на уменьшение генерации мусора. Хотя, флеймграфы неинтерактивные, проверить отдельные выводы нельзя (прошу учесть в следующих этапах, чтобы не терять баллы)

Поэтому 8 баллов

И перед мержем необходимо откатить лишние изменения

import java.util.NoSuchElementException;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.*;
Copy link
Member

Choose a reason for hiding this comment

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

Необходимо откатить изменения в несвязанных с этапом файлах. Здесь и в еще одном классе reference/dao

private static final String ID = "id=";
private final ReferenceDao dao;

public ServerImpl(ServiceConfig config) throws IOException {
Copy link
Member

Choose a reason for hiding this comment

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

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

return serverConfig;
}

public Response get(final Request request) {
Copy link
Member

Choose a reason for hiding this comment

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

Методы get,put,delete и createServerConfig являются публичными, хотя этого не требуется. Нужно ужесточить доступность/видимость


int method = request.getMethod();

Response response = switch (method) {
Copy link
Member

Choose a reason for hiding this comment

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

Для всех методов отсутствует обработка исключений от DAO

Что, кстати, будет при выбросе исключения?) Автоматом 500 ответ или, может, отсутствие ответа?)

Comment on lines 124 to 128
dao.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
super.stop();
Copy link
Member

Choose a reason for hiding this comment

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

Сначала закрывается dao, затем сервер перестаёт слушать порт
Получается, что будет попытка обработать часть запросов уже с закрытым dao
Поэтому, нужно сначала прекратить принимать http запросы, а уже потом закрывать dao

* Результаты работы wrk2 при стабильной нагрузкe на протяжении 2х минут: ![](./get/120_2550_get_before.png)

### Профилирование запросов типа PUT:
* Профилирование CPU: ![](profile_cpu_put_before.png)
Copy link
Member

Choose a reason for hiding this comment

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

Высокая доля сэмплов от работы JVM может свидетельствовать о том, что JVM не была "прогрета" перед началом профилирования. Начинать снимать профили имеет смысл, когда уже было выполнено какое-то количество вставок в базу, прошло, скажем, секунд 30. Тогда горячий код успеет скомпилироваться

* Убрана двойная аллокация через getPath()

Попытка оптимизировать возвращение результата с кодом OK и body:
* Было замечено, что в используемом конструкторе Response() происходит двойная аллокация строки "Content-Length: " + body.length (на FlameGraph видно вызов метода StringConcatHelper.newString()).
Copy link
Member

Choose a reason for hiding this comment

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

Зря профили были экспортированы в SVG. Потерялась интерактивность, у ревьюера нет возможности их внимательно изучить

в частности, хотелось полученный вывод о двойной аллокации проверить


public class ServiceImpl implements Service {
private final ServiceConfig serviceConfig;
private ServerImpl server;
Copy link
Member

Choose a reason for hiding this comment

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

Вероятно, здесь будет достаточно HttpServer/Server

acceptorConfig.port = config.selfPort();
acceptorConfig.reusePort = true;

HttpServerConfig serverConfig = new HttpServerConfig();
Copy link

Choose a reason for hiding this comment

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

Rename "serverConfig" which hides the field declared at line 18.

@Queenore
Copy link
Contributor Author

Исправил замечания.

public ServerImpl(HttpServerConfig config, Config daoConfig) throws IOException {
super(config);

this.dao = new PersistentReferenceDao(daoConfig);
Copy link
Member

Choose a reason for hiding this comment

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

Dao, в принципе, тоже можно было бы инстанцировать в сервисе и в сервер просто инжектить

@lamtev lamtev self-requested a review February 29, 2024 08:59
@lamtev lamtev merged commit d30ecb0 into polis-vk:main Feb 29, 2024
2 checks passed
osokindm pushed a commit to osokindm/2024-highload-dht that referenced this pull request Mar 6, 2024
* rename package

* 8/14 tests

* 12/14 tests

* 14/14 tests

* fixes

* fixes

* fixes

* + report

* codestyle fixes

* codestyle fixes

* add lua scripts

* report fix

* HTML to SVG

* add THRESHOLD_BYTES const

* code review fixes

* code climate fixes

* style fixes

---------

Co-authored-by: Anton Lamtev <lamtev@users.noreply.github.com>
axothy pushed a commit to axothy/2024-highload-dht that referenced this pull request Mar 13, 2024
* rename package

* 8/14 tests

* 12/14 tests

* 14/14 tests

* fixes

* fixes

* fixes

* + report

* codestyle fixes

* codestyle fixes

* add lua scripts

* report fix

* HTML to SVG

* add THRESHOLD_BYTES const

* code review fixes

* code climate fixes

* style fixes

---------

Co-authored-by: Anton Lamtev <lamtev@users.noreply.github.com>
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.

2 participants