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

[v4] Composition engine #404

Open
wants to merge 18 commits into
base: v4
Choose a base branch
from
Open

[v4] Composition engine #404

wants to merge 18 commits into from

Conversation

bonkalol
Copy link
Member

@bonkalol bonkalol commented Apr 8, 2024

No description provided.

@bonkalol bonkalol changed the title WIP: Composition engine Composition engine Apr 8, 2024
@bonkalol bonkalol requested a review from kobezzza April 8, 2024 16:47
@bonkalol bonkalol changed the title Composition engine [v4] Composition engine Apr 9, 2024
{cacheKey} = r.ctx;

if (cacheKey != null && !r.destroyed) {
boundedRequests.set(cacheKey, r);
Copy link
Member Author

Choose a reason for hiding this comment

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

@kobezzza вот тут не уверен, но лучше ничего не придумал

Мне нужно собирать request которые сделал движок чтобы при вызове engine.dropCache или engine.destroy вызывать эти же методы у всех запросов которые были созданы движком. Соответственно чтобы это сделать я держу карту [cacheKey: request] в которой сохраняю созданные запросы.

Может возникнуть коллизия и тогда старый request будет заменен свежесозданным, это ок? Не создам ли я учетек памяти тут?

Copy link
Contributor

Choose a reason for hiding this comment

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

Тут проще завести локальный асинк и в момент создания каждого запроса просто регать воркер, а потом в финальном деструкторе сделать claerAll

@bonkalol bonkalol requested a review from kobezzza May 17, 2024 14:24
error;

try {
result = await request('', {engine}).data;
Copy link
Member Author

@bonkalol bonkalol May 17, 2024

Choose a reason for hiding this comment

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

@kobezzza

Сейчас сигнатурой request не предусмотрена возможность не передавать url запроса, что в целом то логично.

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

const
requestFilter = provider.requestFilter?.(options, params);

if (requestFilter === false) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Может просто завернуть в Promise.resolve и тогда получится простая логика: есть фильтр и нет фильтра

}, reject);

function boundRequest<T extends Provider | RequestResponseObject | RequestPromise>(request: T): T {
if (request instanceof Provider) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Тут надо ввести контракт, что если есть методы dropCache или destroy, а не смотреть на инстанс реквеста

const resultPromise = (() => {
if (opts?.aggregateErrors) {
return Promise.allSettled(promises)
.then((results) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

Вынеси колбек как отдельно функцию


r.destroy = (...args) => {
boundedRequests.delete(cacheKey);
forkedDestroy(...args);
Copy link
Contributor

Choose a reason for hiding this comment

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

this потерял

const response = new Response(result, {
parent: options.parent,
important: options.important,
responseType: 'json',
Copy link
Contributor

Choose a reason for hiding this comment

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

А почему json , а не object?

context = params.opts.meta.provider ?? params.ctx,
providerParams = context instanceof Provider ? context.params : undefined;

if (context instanceof Provider && !providersWithEngine.has(context)) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Почему проверка именно на провайдера? тут мне кажется надо просто смотреть утиной типизацией наличие методов

boundedRequests = new Map<string, RequestResponseObject>();

const
providersWithEngine = new WeakSet();
Copy link
Contributor

Choose a reason for hiding this comment

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

А это зачем?

});

engine.dropCache = (recursive) => {
boundedRequests.forEach((request) => request.dropCache(recursive));
Copy link
Contributor

Choose a reason for hiding this comment

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

Мне не нравиться, что ты явно разделяешь сущности - запрос и провайдер. Это должно быть без разницы. Можно воспользроваться асинк: он умеет работать как с воркерами, так и с абртабл промисами и т.д.

```typescript
const r = request({engine: compositionEngine([
{
request: (opts, params, {boundRequest}) => boundRequest(request('http://locahost:5555/json/1')),
Copy link
Contributor

Choose a reason for hiding this comment

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

А нельзя избавиться от потребности явно вызывать bound?


}

const val1 = await boundRequest(new Provider1()).get().data;
Copy link
Contributor

Choose a reason for hiding this comment

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

Вот тут кейс валидный

@@ -35,6 +35,8 @@ import type { RequestEngine, RequestOptions } from 'core/request/interface';
import { availableParams, deniedProviderParams } from 'core/request/engines/provider/const';
import type { AvailableOptions, MethodsMapping, Meta } from 'core/request/engines/provider/interface';

export * from 'core/request/engines/composition';
Copy link
Contributor

Choose a reason for hiding this comment

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

А зачем это?

@@ -155,6 +155,11 @@ export interface RequestResponseObject<D = unknown> {
* Destroys the request context
*/
destroy(): void;

Copy link
Contributor

Choose a reason for hiding this comment

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

А зачем это?

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.

None yet

2 participants