Skip to content

Conversation

@Stivo182
Copy link
Owner

@Stivo182 Stivo182 commented Oct 8, 2025

Summary by CodeRabbit

  • New Features

    • Added support for custom endpoints/controllers loaded from a file or directory.
    • Introduced CLI option --routes-handlers to specify paths to custom controllers.
    • Added programmatic API to set and read the controllers location.
  • Documentation

    • Added a “Кастомные эндпоинты” section with setup examples (CLI and code).
    • Documented the new CLI option and public API for controller location.
    • Updated navigation order in README.
  • Tests

    • Added tests to verify launching with custom controllers from both a file and a directory.

@coderabbitai
Copy link

coderabbitai bot commented Oct 8, 2025

Walkthrough

Adds support for custom controllers via a new CLI flag and API. Introduces a service launcher, a connector that discovers/loads controller scripts from files or directories, updates HttpBin to pass the controllers path to the child process, adjusts command startup, updates README, and adds tests and fixtures for custom routes.

Changes

Cohort / File(s) Summary
Documentation
README.md
Reordered navigation, documented CLI option --routes-handlers, added public API docs for controller path getters/setters, and added a new section detailing custom endpoints with examples.
Core API: HttpBin
src/core/Классы/HttpBin.os
Added private _РасположениеКонтроллеров; new exports УстановитьРасположениеКонтроллеров(Расположение) and РасположениеКонтроллеров(); updated process launch to append --routes-handlers "<path>" when set.
CLI Command and Startup Refactor
src/cmd/Классы/КомандаЗапустить.os
Added CLI option routes-handlers; introduced _КастомныеКонтроллеры and _ЗапускательСервиса; replaced direct web app launch with _ЗапускательСервиса.Запустить(_Хост, _Порт); removed legacy server settings gating.
Service Launcher (new)
src/internal/Классы/ЗапускательСервиса.os
New module exporting Запустить(Хост, Порт); configures server settings (host, port, optional test delay) and invokes underlying web app launcher.
Custom Controllers Connector (new)
src/internal/Классы/ПодключательКастомныхКонтроллеров.os
New module to parse --routes-handlers args, resolve files/dirs, and connect .os controller scripts; exports НайтиИПодключить, Подключить, ПодключитьИзКаталога, НайтиФайлыИзПереданныхАргументов.
Command Entrypoint
src/cmd/main.os
Imports internal modules, instantiates ПодключательКастомныхКонтроллеров, and calls НайтиИПодключить() before starting the app.
App Controller Adjustments
src/app/ОсновнойКонтроллер.os
Removed now-unneeded ../internal usage directive; no functional changes to controller logic.
Tests and Fixtures
tests/HttpBin_test.os, tests/fixtures/КастомныеКонтроллеры/КастомныйКонтроллер.os
Added tests for launching with custom controllers from a file and a directory; added example controller responding "success" at /order/add.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant User as User
  participant CLI as cmd/main.os
  participant Conn as ПодключательКастомныхКонтроллеров
  participant Svc as ЗапускательСервиса
  participant Web as ВебПриложение

  User->>CLI: Run with args (--routes-handlers [paths], host, port)
  CLI->>Conn: НайтиИПодключить()
  Conn->>Conn: НайтиФайлыИзПереданныхАргументов()
  alt path is directory
    Conn->>Conn: ПодключитьИзКаталога(каталог .os)
    loop each .os
      Conn->>Conn: Подключить(файл)
      Conn->>Web: ПодключитьСценарий(имя без расширения)
    end
  else path is file
    Conn->>Conn: Подключить(файл)
    Conn->>Web: ПодключитьСценарий(имя без расширения)
  else not found
    Conn-->>CLI: Исключение (путь не существует)
  end
  CLI->>Svc: Запустить(хост, порт)
  Svc->>Svc: НастроитьВебСервер()
  Svc->>Web: Запустить()
  Web-->>User: Сервис запущен, маршруты доступны
Loading
sequenceDiagram
  autonumber
  participant Test as tests
  participant HttpBin as core/Классы/HttpBin
  participant Proc as Child Process

  Test->>HttpBin: УстановитьРасположениеКонтроллеров(путь)
  HttpBin->>HttpBin: сохранить _РасположениеКонтроллеров
  Test->>HttpBin: ЗапуститьПроцесс()
  alt controllers path set
    HttpBin->>HttpBin: добавить аргументы --routes-handlers "путь"
  end
  HttpBin->>Proc: старт процесса с аргументами
  Proc-->>Test: сервис доступен
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

I nibble code like clover sprigs,
New routes hop in on nimble legs.
A flag unfurls — --routes-handlers bright,
Controllers bloom in day and night.
I thump the ground: “It’s all aligned!”
Now /order/add returns refined — success! 🥕

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title “feat: Поддержка кастомных эндпоинтов” clearly and succinctly summarizes the main change—adding support for custom endpoints—without unrelated noise, ensuring reviewers immediately understand the primary feature introduced.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/custom-routes-handlers

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@Stivo182
Copy link
Owner Author

Stivo182 commented Oct 8, 2025

@coderabbitai review

@coderabbitai
Copy link

coderabbitai bot commented Oct 8, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

@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

🧹 Nitpick comments (7)
src/internal/Классы/ПодключательКастомныхКонтроллеров.os (1)

50-58: Consider handling empty directories explicitly.

The procedure silently succeeds when a directory contains no .os files. While this might be intentional, it could lead to confusion if a user expects controllers to be loaded but none are found.

Consider adding a log message or validation to inform users when no controllers are found in a specified directory.

Apply this diff to add informative logging:

 Процедура ПодключитьИзКаталога(Каталог)

 	Файлы = НайтиФайлы(Каталог, "*.os");
+	
+	Если Файлы.Количество() = 0 Тогда
+		Сообщить(СтрШаблон("Предупреждение: в каталоге '%1' не найдено файлов контроллеров (*.os)", Каталог));
+	КонецЕсли;

 	Для Каждого Файл Из Файлы Цикл
 		Подключить(Файл.ПолноеИмя);
 	КонецЦикла;
 	
 КонецПроцедуры
src/cmd/main.os (1)

4-7: Connector wiring before app start looks good. Optional: add contextful error on failure.

Wrapping in try/catch will surface clearer diagnostics if a bad path is passed.

-ПодключательКастомныхКонтроллеров = Новый ПодключательКастомныхКонтроллеров();
-ПодключательКастомныхКонтроллеров.НайтиИПодключить();
+Попытка
+	ПодключательКастомныхКонтроллеров = Новый ПодключательКастомныхКонтроллеров();
+	ПодключательКастомныхКонтроллеров.НайтиИПодключить();
+Исключение
+	ВызватьИсключение СтрШаблон("Ошибка подключения кастомных контроллеров: %1",
+		КраткоеПредставлениеОшибки(ИнформацияОбОшибке()));
+КонецПопытки;
tests/HttpBin_test.os (1)

50-79: Good coverage for file/dir handlers. Strengthen assertions and increase timeout to reduce flakiness.

Also assert HTTP 200 and use 10s timeout for CI stability.

-	Ответ = КоннекторHTTP.Get(HttpBin.URL("/order/add"), , Новый Структура("Таймаут", 3)).Текст();
+	Ответ = КоннекторHTTP.Get(HttpBin.URL("/order/add"), , Новый Структура("Таймаут", 10));
+	Ожидаем.Что(Ответ.КодСостояния).Равно(200);
+	Текст = Ответ.Текст();

-	Ожидаем.Что(Ответ).Равно("success");
+	Ожидаем.Что(Текст).Равно("success");
-	Ответ = КоннекторHTTP.Get(HttpBin.URL("/order/add"), , Новый Структура("Таймаут", 3)).Текст();
+	Ответ = КоннекторHTTP.Get(HttpBin.URL("/order/add"), , Новый Структура("Таймаут", 10));
+	Ожидаем.Что(Ответ.КодСостояния).Равно(200);
+	Текст = Ответ.Текст();

-	Ожидаем.Что(Ответ).Равно("success");
+	Ожидаем.Что(Текст).Равно("success");
src/internal/Классы/ЗапускательСервиса.os (1)

39-41: Make test-mode env check case-insensitive.

Accept TRUE/true/True to avoid surprises.

-	Если ПолучитьПеременнуюСреды("HTTPBIN_IS_TEST_MODE") = "true" Тогда
+	Если СтрНРег(ПолучитьПеременнуюСреды("HTTPBIN_IS_TEST_MODE")) = "true" Тогда
 		_НастройкиВебСервера.ЗадержкаПередЧтениемСокета = 400;
 	КонецЕсли;
src/core/Классы/HttpBin.os (1)

201-213: Validate and normalize controllers path in setter.

Fail fast with a clear message and pass a normalized path to the child process.

-Функция УстановитьРасположениеКонтроллеров(Расположение) Экспорт
-	_РасположениеКонтроллеров = Расположение;
-	Возврат ЭтотОбъект;
-КонецФункции
+Функция УстановитьРасположениеКонтроллеров(Расположение) Экспорт
+	Если Не ФС.ФайлСуществует(Расположение) И Не ФС.КаталогСуществует(Расположение) Тогда
+		ВызватьИсключение СтрШаблон("Указанный путь к контроллерам не существует: %1", Расположение);
+	КонецЕсли;
+	_РасположениеКонтроллеров = ФС.НормализоватьПуть(Расположение);
+	Возврат ЭтотОбъект;
+КонецФункции
README.md (1)

137-177: Fix markdown lint: use headings instead of emphasized text.

Converts emphasized lines to H4 to satisfy MD036.

-**Пример контроллера**
+#### Пример контроллера
...
-**Через программный интерфейс**
+#### Через программный интерфейс
...
-**Через CLI**
+#### Через CLI
src/cmd/Классы/КомандаЗапустить.os (1)

61-63: Invoke controller connector in Run command, not in main
Scoping connector invocation to the run subcommand avoids unintended side effects for other commands (e.g., help).

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3d94b80 and 488de34.

📒 Files selected for processing (9)
  • README.md (3 hunks)
  • src/app/ОсновнойКонтроллер.os (0 hunks)
  • src/cmd/main.os (1 hunks)
  • src/cmd/Классы/КомандаЗапустить.os (2 hunks)
  • src/core/Классы/HttpBin.os (3 hunks)
  • src/internal/Классы/ЗапускательСервиса.os (1 hunks)
  • src/internal/Классы/ПодключательКастомныхКонтроллеров.os (1 hunks)
  • tests/HttpBin_test.os (3 hunks)
  • tests/fixtures/КастомныеКонтроллеры/КастомныйКонтроллер.os (1 hunks)
💤 Files with no reviewable changes (1)
  • src/app/ОсновнойКонтроллер.os
🧰 Additional context used
🪛 markdownlint-cli2 (0.18.1)
README.md

148-148: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


163-163: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


173-173: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: test (stable) / build (ubuntu-latest, stable)
🔇 Additional comments (6)
src/internal/Классы/ПодключательКастомныхКонтроллеров.os (2)

30-44: LGTM!

The procedure correctly handles controller connection with proper error context. The documentation is clear and follows standard conventions.


50-58: AI summary incorrectly lists internal procedures as exported.

The AI summary claims ПодключитьИзКаталога() and НайтиФайлыИзПереданныхАргументов() are exported procedures, but the code correctly defines them as internal helpers without the Экспорт keyword. These procedures are appropriately placed in the #Область СлужебныеПроцедурыИФункции section and should remain internal.

Also applies to: 60-81

tests/fixtures/КастомныеКонтроллеры/КастомныйКонтроллер.os (1)

1-8: Fixture is minimal and correct.

src/core/Классы/HttpBin.os (1)

269-272: CLI arg injection for routes-handlers looks correct.

Good use of platform-aware quoting to preserve spaces in paths.

src/cmd/Классы/КомандаЗапустить.os (1)

29-35: Declaring routes-handlers option is correct, even if unused.

Keeps CLI parser aware of the flag; good to suppress unused warning.

src/internal/Классы/ЗапускательСервиса.os (1)

35-35: Verify that setting НастройкиВебСервера.РазмерБуфера to 0 is supported by the platform. If 0 isn’t a valid or special value, remove this assignment to use the default buffer size.

Comment on lines +60 to +81
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Fix argument parsing to collect all values after the flag.

The current implementation only collects ONE value immediately after each --routes-handlers flag occurrence. If a user passes multiple paths like --routes-handlers file1.os file2.os, only file1.os will be collected and file2.os will be silently dropped.

This silent data loss can lead to confusion and missing controller registrations.

Apply this diff to collect all values after the flag until the next flag is encountered:

 Функция НайтиФайлыИзПереданныхАргументов()

 	Файлы = Новый Массив();

 	НайденКлюч = Ложь;
 	Для Каждого Значение Из АргументыКоманднойСтроки Цикл

+		Если СтрНачинаетсяС(Значение, "--") Тогда
+			Если Значение = "--routes-handlers" Тогда
+				НайденКлюч = Истина;
+			Иначе
+				НайденКлюч = Ложь;
+			КонецЕсли;
+			Продолжить;
+		КонецЕсли;
+
 		Если НайденКлюч Тогда
 			Файлы.Добавить(Значение);
-			НайденКлюч = Ложь;
-			Продолжить;
 		КонецЕсли;

-		Если Значение = "--routes-handlers" Тогда
-			НайденКлюч = Истина;
-		КонецЕсли;
-
 	КонецЦикла;

 	Возврат Файлы;

 КонецФункции

This change allows collecting multiple paths: --routes-handlers file1.os file2.os file3.os while still supporting repeated flags: --routes-handlers file1.os --routes-handlers file2.os.

🤖 Prompt for AI Agents
In src/internal/Классы/ПодключательКастомныхКонтроллеров.os around lines 60-81,
the current loop sets НайденКлюч true only to add a single following value then
clears it, so subsequent values after the flag are ignored; change the parsing
so that when "--routes-handlers" is seen you set НайденКлюч = Истина and then
for each following argument, if НайденКлюч and the argument does NOT start with
"-" (i.e., is not another flag) add it to Файлы and keep НайденКлюч true; if the
argument starts with "-" treat it as a new flag by setting НайденКлюч = Ложь and
re-evaluating that argument as a flag (do not consume it as a value). This
collects multiple paths after one flag and still supports repeated flags.

@Stivo182 Stivo182 merged commit 95203ca into v2.0.0 Oct 8, 2025
21 of 22 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Oct 8, 2025
@Stivo182 Stivo182 deleted the feat/custom-routes-handlers branch October 8, 2025 16:19
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