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

Sentry ID отправляется для показа клиенту #3416

Merged
merged 1 commit into from
Feb 12, 2025

Conversation

nixel2007
Copy link
Member

@nixel2007 nixel2007 commented Feb 12, 2025

Описание

Связанные задачи

Closes

Чеклист

Общие

  • Ветка PR обновлена из develop
  • Отладочные, закомментированные и прочие, не имеющие смысла участки кода удалены
  • Изменения покрыты тестами
  • Обязательные действия перед коммитом выполнены (запускал команду gradlew precommit)

Для диагностик

  • Описание диагностики заполнено для обоих языков (присутствуют файлы для обоих языков, для русского заполнено все подробно, перевод на английский можно опустить)

Дополнительно

Copy link
Contributor

coderabbitai bot commented Feb 12, 2025

Warning

Rate limit exceeded

@nixel2007 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 19 minutes and 21 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 5843cb0 and 22f33f8.

📒 Files selected for processing (3)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/SentryAspect.java (3 hunks)
  • src/main/resources/com/github/_1c_syntax/bsl/languageserver/aop/SentryAspect_en.properties (1 hunks)
  • src/main/resources/com/github/_1c_syntax/bsl/languageserver/aop/SentryAspect_ru.properties (1 hunks)

"""

Walkthrough

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

Changes

Файл(ы) Изменения
build.gradle.kts Добавлен условный блок для настройки Sentry-плагина: при значении SENTRY_AUTH_TOKEN, отличном от "true", включается опция includeSourceContext для улучшения отчетности об ошибках.
.../SentryAspect.java Добавлен новый метод logException для централизованного логирования исключений, а также внедрены новые поля languageClientHolder и resources для установления связи с языковым клиентом.

Sequence Diagram(s)

sequenceDiagram
    participant E as Исключение
    participant A as SentryAspect
    participant S as Sentry
    participant L as LanguageClientHolder
    participant Log as LOGGER

    E->>A: Исключение передано в logException
    A->>S: captureException(ex)
    S-->>A: Возвращает sentryId
    alt sentryId валиден
       A->>L: Проверка подключения клиента и отправка сообщения
       L-->>A: Подтверждение отправки
       A->>Log: Запись информационного лога
    else sentryId невалиден
       A->>Log: Запись информационного лога без отправки клиенту
    end
Loading

Poem

Я заяц-кодер, скачущего вальс веду,
Где строки кода как морковки светят в тьму.
Исключения ловлю ловко, бегут прочь баги,
С Sentry и клиентом вместе в хоровод баги.
Пусть код поёт, как песня — радость в каждом шаге!
🥕✨
"""


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d59aa41 and 0160d4f.

📒 Files selected for processing (2)
  • build.gradle.kts (1 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/SentryAspect.java (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: build
  • GitHub Check: Analyse
  • GitHub Check: Benchmark
  • GitHub Check: Analyze the repo with CodeSee
  • GitHub Check: build (23, macOS-latest)
  • GitHub Check: build (23, windows-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build
🔇 Additional comments (3)
src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/SentryAspect.java (2)

53-58: Корректное объявление полей!

Поля правильно аннотированы для внедрения зависимостей. Хорошо, что учтена возможность null для languageClientHolder.


70-81: Отличная централизация обработки исключений!

Вынесение логики в отдельный метод logException улучшает поддерживаемость кода и устраняет дублирование.

build.gradle.kts (1)

278-282: Проверьте условие конфигурации Sentry

Текущее условие выглядит нелогичным:

  • SENTRY_AUTH_TOKEN обычно содержит строку авторизации, а не булево значение
  • Сравнение с "true" может привести к неожиданному поведению

Рекомендуется уточнить условие:

-if (System.getenv("SENTRY_AUTH_TOKEN") != "true") {
+if (System.getenv("ENABLE_SENTRY_SOURCE_CONTEXT") == "true") {

@nixel2007 nixel2007 force-pushed the feature/send-sentry-id-to-client branch from 0160d4f to 5843cb0 Compare February 12, 2025 21:53
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/SentryAspect.java (1)

83-98: ⚠️ Potential issue

Требуется обработка исключений при коммуникации с клиентом

Метод logException хорошо структурирован, но отсутствует обработка исключений при отправке сообщения клиенту.

Добавьте обработку исключений:

-      languageClientHolder.execIfConnected(languageClient -> languageClient.showMessage(messageParams));
+      try {
+        languageClientHolder.execIfConnected(languageClient -> languageClient.showMessage(messageParams));
+      } catch (Exception e) {
+        LOGGER.error("Ошибка при отправке сообщения клиенту", e);
+      }

Также рекомендуется добавить логирование ID события Sentry:

       SentryId sentryId = Sentry.captureException(ex);
+      LOGGER.debug("Создано событие Sentry с ID: {}", sentryId);
       if (sentryId.equals(SentryId.EMPTY_ID)) {
🧹 Nitpick comments (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/SentryAspect.java (1)

24-59: Одобрено с рекомендацией добавить логгер

Корректная настройка внедрения зависимостей с использованием @Setter и @Autowired. Аннотация @checkfornull правильно указывает на возможное отсутствие инициализации languageClientHolder.

Рекомендуется добавить объявление логгера для улучшения отладки:

+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;

 @Aspect
 @NoArgsConstructor
 public class SentryAspect {
+    private static final Logger LOGGER = LoggerFactory.getLogger(SentryAspect.class);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0160d4f and 5843cb0.

📒 Files selected for processing (2)
  • build.gradle.kts (1 hunks)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/SentryAspect.java (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • build.gradle.kts
⏰ Context from checks skipped due to timeout of 90000ms (16)
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (17, ubuntu-latest)
  • GitHub Check: Benchmark
  • GitHub Check: build (23, macOS-latest)
  • GitHub Check: build (23, windows-latest)
  • GitHub Check: build (23, ubuntu-latest)
  • GitHub Check: build (21, macOS-latest)
  • GitHub Check: build (21, windows-latest)
  • GitHub Check: build (21, ubuntu-latest)
  • GitHub Check: build (17, macOS-latest)
  • GitHub Check: build (17, windows-latest)
  • GitHub Check: build (17, ubuntu-latest)
🔇 Additional comments (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/SentryAspect.java (1)

70-81: Улучшена централизация обработки исключений

Изменения улучшают поддерживаемость кода за счет централизации логики обработки исключений в методе logException.

@nixel2007 nixel2007 force-pushed the feature/send-sentry-id-to-client branch 3 times, most recently from 7dd00b4 to 60a03c0 Compare February 12, 2025 21:58
@nixel2007 nixel2007 force-pushed the feature/send-sentry-id-to-client branch from 60a03c0 to 22f33f8 Compare February 12, 2025 21:58
Copy link

Quality Gate Failed Quality Gate failed

Failed conditions
44.4% Coverage on New Code (required ≥ 80%)

See analysis details on SonarQube Cloud

@nixel2007 nixel2007 merged commit de6cea6 into develop Feb 12, 2025
36 of 37 checks passed
@nixel2007 nixel2007 deleted the feature/send-sentry-id-to-client branch February 12, 2025 23:00
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.

1 participant