-
Notifications
You must be signed in to change notification settings - Fork 2
feat: Поддержка кастомных эндпоинтов #15
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
Conversation
WalkthroughAdds 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
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: Сервис запущен, маршруты доступны
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: сервис доступен
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches🧪 Generate unit tests (beta)
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. Comment |
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this 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
.osfiles. 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** +#### Через CLIsrc/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
📒 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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
Summary by CodeRabbit
New Features
Documentation
Tests