Compare commits

...

35 Commits

Author SHA1 Message Date
f9b5c897cf 3.1.2 2024-10-14 01:31:58 +02:00
1a92aa6630 fix(core): Fix incorrect backpressure logic in VirtualStream class 2024-10-14 01:31:58 +02:00
70e2dcc1b8 3.1.1 2024-10-14 00:13:29 +02:00
7b6fb9e9bc fix(virtualstream): Fix handling of virtual streams for proper shutdown 2024-10-14 00:13:28 +02:00
03c7150b6b 3.1.0 2024-10-11 02:15:46 +02:00
83cd25d5a2 feat(virtualstream): Enhance VirtualStream with optional closure when reading from webstream 2024-10-11 02:15:45 +02:00
04d60e6a95 3.0.33 2024-10-11 02:09:51 +02:00
549719ede6 fix(test): Increase delay duration before stopping the server in test suite. 2024-10-11 02:09:50 +02:00
855663eea9 3.0.32 2024-09-06 13:46:10 +02:00
4d98915dbd fix(virtualstream): Fix keep-alive loop handling and test cleanup 2024-09-06 13:46:09 +02:00
f461f16bfd 3.0.31 2024-09-06 13:02:05 +02:00
6beadb8cfc fix(core): Updated dependencies and added close method to VirtualStream 2024-09-06 13:02:04 +02:00
360c8a618b 3.0.30 2024-05-31 22:41:18 +02:00
c03854a9fc fix(core): update 2024-05-31 22:41:17 +02:00
cebd903c9b 3.0.29 2024-05-31 16:34:55 +02:00
e7cf5b7694 fix(error handling): now alos logs the method that an error has been given to. 2024-05-31 16:34:54 +02:00
839bd138c1 3.0.28 2024-05-30 22:47:03 +02:00
e1c721d511 fix(core): update 2024-05-30 22:47:02 +02:00
7ce3f83d54 3.0.27 2024-05-30 22:41:50 +02:00
2e0c6400e8 fix(core): update 2024-05-30 22:41:49 +02:00
58637ed90e 3.0.26 2024-05-30 19:01:40 +02:00
489fa237b9 fix(core): update 2024-05-30 19:01:39 +02:00
4449c82611 3.0.25 2024-05-25 02:18:46 +02:00
fe31a779e4 fix(core): update 2024-05-25 02:18:46 +02:00
9b96c22d6a 3.0.24 2024-05-25 02:15:09 +02:00
262891ccf3 fix(core): update 2024-05-25 02:15:08 +02:00
0d60b29ff7 3.0.23 2024-05-05 17:15:44 +02:00
ecca2a9f32 fix(core): update 2024-05-05 17:15:44 +02:00
3643e5e753 3.0.22 2024-05-05 16:42:22 +02:00
4cba418f13 fix(core): update 2024-05-05 16:42:22 +02:00
a966b0735c 3.0.21 2024-04-17 20:35:42 +02:00
6fed2cdc5c fix(core): update 2024-04-17 20:35:41 +02:00
9fd6bbfc89 3.0.20 2024-04-17 20:17:46 +02:00
e7a7e1c903 fix(core): update 2024-04-17 20:17:45 +02:00
5e5f4003e0 update documentation 2024-04-14 18:58:55 +02:00
18 changed files with 5239 additions and 3846 deletions

48
changelog.md Normal file
View File

@ -0,0 +1,48 @@
# Changelog
## 2024-10-14 - 3.1.2 - fix(core)
Fix incorrect backpressure logic in VirtualStream class
- Corrected the logic for determining backpressure status by checking the available space in the receiveBackpressuredArray.
- Introduced a looping mechanism to wait when the other side is backpressured before sending more data.
## 2024-10-14 - 3.1.1 - fix(virtualstream)
Fix handling of virtual streams for proper shutdown
- Ensured that writeToWebstream method checks for remaining items in receiveBackpressuredArray before closing.
- Corrected package.json dependency for @push.rocks/tapbundle.
- Updated @types/node to version 22.7.5.
## 2024-10-11 - 3.1.0 - feat(virtualstream)
Enhance VirtualStream with optional closure when reading from webstream
- Added an optional parameter `closeAfterReading` to the `readFromWebstream` method.
- The stream will close automatically after reading if `closeAfterReading` is set to true.
## 2024-10-11 - 3.0.33 - fix(test)
Increase delay duration before stopping the server in test suite.
- Adjusted the delay time from 1000 ms to 10000 ms before stopping the server to ensure tests complete smoothly.
## 2024-09-06 - 3.0.32 - fix(virtualstream)
Fix keep-alive loop handling and test cleanup
- Prevent unnecessary keep-alive loop from starting on the responding side
- Add logging for keep-alive loop initiation in VirtualStream
- Temporarily comment out stream close and tap forceful stop in test to avoid abrupt termination
## 2024-09-06 - 3.0.31 - fix(core)
Updated dependencies and added close method to VirtualStream
- Updated dependencies in package.json for better compatibility
- Added close method to VirtualStream class in ts/classes.virtualstream.ts for more graceful stream termination
## 2024-05-31 - 3.0.28 - Error Handling
Enhancement to error handling mechanisms.
- Logs now include the method to which an error was given.
## 2023-08-04 - 3.0.0 - Core
Introduced a breaking change.
- Major update to core functionalities.

View File

@ -2,17 +2,33 @@
"gitzone": {
"projectType": "npm",
"module": {
"githost": "gitlab.com",
"githost": "code.foss.global",
"gitscope": "api.global",
"gitrepo": "typedrequest",
"description": "make typed requests towards apis",
"description": "A TypeScript library for making typed requests towards APIs, including facilities for handling requests, routing, and virtual stream handling.",
"npmPackagename": "@api.global/typedrequest",
"license": "MIT",
"projectDomain": "api.global"
"projectDomain": "api.global",
"keywords": [
"TypeScript",
"API Requests",
"HTTP",
"Typed Programming",
"Request Routing",
"Response Handling",
"Virtual Streams",
"Asynchronous",
"Network Communication",
"Server Communication",
"API Integration"
]
}
},
"npmci": {
"npmGlobalTools": [],
"npmAccessLevel": "public"
},
"tsdoc": {
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n"
}
}

View File

@ -1,8 +1,8 @@
{
"name": "@api.global/typedrequest",
"version": "3.0.19",
"version": "3.1.2",
"private": false,
"description": "make typed requests towards apis",
"description": "A TypeScript library for making typed requests towards APIs, including facilities for handling requests, routing, and virtual stream handling.",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"type": "module",
@ -14,24 +14,25 @@
"buildDocs": "tsdoc"
},
"devDependencies": {
"@api.global/typedserver": "^3.0.27",
"@git.zone/tsbuild": "^2.1.72",
"@api.global/typedserver": "^3.0.51",
"@git.zone/tsbuild": "^2.1.84",
"@git.zone/tsbundle": "^2.0.15",
"@git.zone/tsrun": "^1.2.44",
"@git.zone/tstest": "^1.0.86",
"@git.zone/tsrun": "^1.2.49",
"@git.zone/tstest": "^1.0.90",
"@push.rocks/smartenv": "^5.0.12",
"@push.rocks/tapbundle": "^5.0.15",
"@types/node": "^20.11.24"
"@push.rocks/tapbundle": "^5.3.0",
"@types/node": "^22.7.5"
},
"dependencies": {
"@api.global/typedrequest-interfaces": "^3.0.18",
"@api.global/typedrequest-interfaces": "^3.0.19",
"@push.rocks/isounique": "^1.0.5",
"@push.rocks/lik": "^6.0.14",
"@push.rocks/smartbuffer": "^1.0.7",
"@push.rocks/lik": "^6.1.0",
"@push.rocks/smartbuffer": "^3.0.4",
"@push.rocks/smartdelay": "^3.0.5",
"@push.rocks/smartpromise": "^4.0.3",
"@push.rocks/webrequest": "^3.0.35",
"@push.rocks/webstream": "^1.0.8"
"@push.rocks/smartguard": "^3.1.0",
"@push.rocks/smartpromise": "^4.0.4",
"@push.rocks/webrequest": "^3.0.37",
"@push.rocks/webstream": "^1.0.10"
},
"files": [
"ts/**/*",
@ -47,5 +48,18 @@
],
"browserslist": [
"last 1 chrome versions"
],
"keywords": [
"TypeScript",
"API Requests",
"HTTP",
"Typed Programming",
"Request Routing",
"Response Handling",
"Virtual Streams",
"Asynchronous",
"Network Communication",
"Server Communication",
"API Integration"
]
}

8646
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

1
readme.hints.md Normal file
View File

@ -0,0 +1 @@

214
readme.md
View File

@ -1,109 +1,135 @@
# @apiglobal/typedrequest
make typed requests towards apis
# @api.global/typedrequest
## Availabililty and Links
* [npmjs.org (npm package)](https://www.npmjs.com/package/@apiglobal/typedrequest)
* [gitlab.com (source)](https://gitlab.com/apiglobal/typedrequest)
* [github.com (source mirror)](https://github.com/apiglobal/typedrequest)
* [docs (typedoc)](https://apiglobal.gitlab.io/typedrequest/)
A TypeScript library for making typed requests towards APIs, providing interfaces and classes to handle request/response cycles using typed definitions. It supports building and handling requests, routing based on request types, and virtual stream handling over networks.
## Status for master
## Install
Status Category | Status Badge
-- | --
GitLab Pipelines | [![pipeline status](https://gitlab.com/apiglobal/typedrequest/badges/master/pipeline.svg)](https://lossless.cloud)
GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/apiglobal/typedrequest/badges/master/coverage.svg)](https://lossless.cloud)
npm | [![npm downloads per month](https://badgen.net/npm/dy/@apiglobal/typedrequest)](https://lossless.cloud)
Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/apiglobal/typedrequest)](https://lossless.cloud)
TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud)
node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud)
PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@apiglobal/typedrequest)](https://lossless.cloud)
PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@apiglobal/typedrequest)](https://lossless.cloud)
BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@apiglobal/typedrequest)](https://lossless.cloud)
Platform support | [![Supports Windows 10](https://badgen.net/badge/supports%20Windows%2010/yes/green?icon=windows)](https://lossless.cloud) [![Supports Mac OS X](https://badgen.net/badge/supports%20Mac%20OS%20X/yes/green?icon=apple)](https://lossless.cloud)
To install `@api.global/typedrequest`, you can use npm or yarn. Run the following command in your project directory:
```
npm install @api.global/typedrequest --save
```
Or, if you prefer yarn:
```
yarn add @api.global/typedrequest
```
This package is designed to facilitate making typed requests to APIs, ensuring that both requests and responses adhere to predefined interfaces. This enhances the predictability and reliability of network communication in applications that interact with APIs.
## Usage
Use TypeScript for best in class intellisense.
Utilizing `@api.global/typedrequest` involves several core concepts, including the creation of typed requests, handling virtual streams, defining request handlers, and routing requests based on their type. Below are comprehensive examples and explanations of how to use these features in your applications.
### Setting Up a Typed Request
The foundation of `@api.global/typedrequest` is the `TypedRequest` class, which allows you to define requests that are strictly typed. This ensures that both the request sent and the response received match the expected structures.
First, define an interface that represents your request and response data structure:
```typescript
import { expect, tap } from '@pushrocks/tapbundle';
import * as smartexpress from '@pushrocks/smartexpress';
import * as typedrequest from '../ts/index';
let testServer: smartexpress.Server;
let testTypedHandler: typedrequest.TypedHandler<ITestReqRes>;
// lets define an interface
interface ITestReqRes {
method: 'hi';
request: {
name: string;
};
response: {
surname: string;
};
// Define an interface for your request/response structure
interface IUserRequest {
method: 'getUser';
request: { userId: string };
response: { username: string; email: string; };
}
tap.test('should create a typedHandler', async () => {
// lets use the interface in a TypedHandler
testTypedHandler = new typedrequest.TypedHandler<ITestReqRes>('hi', async (reqArg) => {
return {
surname: 'wow',
};
});
});
tap.test('should spawn a server to test with', async () => {
testServer = new smartexpress.Server({
cors: true,
forceSsl: false,
port: 3000,
});
});
tap.test('should define a testHandler', async () => {
const testTypedRouter = new typedrequest.TypedRouter(); // typed routers can broker typedrequests between handlers
testTypedRouter.addTypedHandler(testTypedHandler);
testServer.addRoute(
'/testroute',
new smartexpress.HandlerTypedRouter(testTypedRouter as any) // the "any" is testspecific, since smartexpress ships with its own version of typedrequest.
);
});
tap.test('should start the server', async () => {
await testServer.start();
});
tap.test('should fire a request', async () => {
const typedRequest = new typedrequest.TypedRequest<ITestReqRes>(
'http://localhost:3000/testroute',
'hi'
);
const response = await typedRequest.fire({
name: 'really',
});
console.log('this is the response:');
console.log(response);
expect(response.surname).to.equal('wow');
});
tap.test('should end the server', async () => {
await testServer.stop();
});
tap.start();
```
## Contribution
Next, create an instance of `TypedRequest` using this interface, and use it to make an API call:
We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :)
```typescript
import { TypedRequest } from '@api.global/typedrequest';
For further information read the linked docs at the top of this readme.
// Construct a TypedRequest instance for fetching user data
const getUserRequest = new TypedRequest<IUserRequest>('https://your-api.com/users', 'getUser');
> MIT licensed | **&copy;** [Lossless GmbH](https://lossless.gmbh)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
// Execute the request with a specific userId and log the response
const userResponse = await getUserRequest.fire({ userId: 'user-123' });
console.log(userResponse.username);
```
[![repo-footer](https://lossless.gitlab.io/publicrelations/repofooter.svg)](https://maintainedby.lossless.com)
### Handling Virtual Streams
`@api.global/typedrequest` introduces the concept of virtual streams, allowing you to manage real-time data transfer over the network as streams. You can create a virtual stream, send data, and read data from it as shown below:
```typescript
import { VirtualStream } from '@api.global/typedrequest';
// Instantiate a VirtualStream for handling real-time data
const myStream = new VirtualStream<ArrayBufferLike>();
// Use the stream to send data
await myStream.sendData(new TextEncoder().encode("Hello, World!"));
// Retrieve data from the stream
const receivedData = await myStream.fetchData();
console.log(new TextDecoder().decode(receivedData));
```
### Defining and Using Handlers
To process requests, you can define handlers that are responsible for specific types of requests:
```typescript
import { TypedHandler } from '@api.global/typedrequest';
interface IAdditionRequest {
method: 'add';
request: { a: number; b: number; };
response: { result: number; };
}
// Create a handler for processing addition requests
const additionHandler = new TypedHandler<IAdditionRequest>('add', async (req) => {
return { result: req.a + req.b };
});
```
### Routing Requests
`TypedRouter` is used to route requests to their appropriate handlers based on the request type:
```typescript
import { TypedRouter } from '@api.global/typedrequest';
const router = new TypedRouter();
// Associate the additionHandler with the router
router.addTypedHandler(additionHandler);
// The router now directs 'add' requests to the additionHandler
```
### Error Handling
`@api.global/typedrequest` provides a `TypedResponseError` class to facilitate error handling in typed requests:
```typescript
import { TypedResponseError } from '@api.global/typedrequest';
// Throw a TypedResponseError with details about the error
throw new TypedResponseError('An error occurred', { detail: 'Error details' });
```
This comprehensive overview covers the essential features provided by `@api.global/typedrequest`. By adhering to defined request and response structures, you can create more reliable and maintainable applications that interact seamlessly with APIs.
## License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
### Company Information
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

View File

@ -44,4 +44,4 @@ tap.skip.test('test', async (tools) => {
await tools.delayFor(5000);
})
tap.start();
export default tap.start();

View File

@ -101,9 +101,9 @@ tap.test('should allow VirtualStreams', async () => {
});
tap.test('should end the server', async (toolsArg) => {
await toolsArg.delayFor(1000);
await toolsArg.delayFor(10000);
await testServer.stop();
setTimeout(() => process.exit(0), 100);
await tap.stopForcefully();
});
tap.start();
export default tap.start();

View File

@ -1,8 +1,8 @@
/**
* autocreated commitinfo by @pushrocks/commitinfo
* autocreated commitinfo by @push.rocks/commitinfo
*/
export const commitinfo = {
name: '@api.global/typedrequest',
version: '3.0.19',
description: 'make typed requests towards apis'
version: '3.1.2',
description: 'A TypeScript library for making typed requests towards APIs, including facilities for handling requests, routing, and virtual stream handling.'
}

View File

@ -1,8 +1,10 @@
import * as plugins from './plugins.js';
import { TypedResponseError } from './typedrequest.classes.typedresponseerror.js';
import { TypedResponseError } from './classes.typedresponseerror.js';
import { TypedTools } from './classes.typedtools.js';
export type THandlerFunction<T extends plugins.typedRequestInterfaces.ITypedRequest> = (
requestArg: T['request']
requestArg: T['request'],
typedToolsArg?: TypedTools
) => Promise<T['response']>;
/**
@ -28,7 +30,8 @@ export class TypedHandler<T extends plugins.typedRequestInterfaces.ITypedRequest
);
}
let typedResponseError: TypedResponseError;
const response = await this.handlerFunction(typedRequestArg.request).catch((e) => {
const typedtoolsInstance = new TypedTools();
const response = await this.handlerFunction(typedRequestArg.request, typedtoolsInstance).catch((e) => {
if (e instanceof TypedResponseError) {
typedResponseError = e;
} else {

View File

@ -1,8 +1,8 @@
import * as plugins from './plugins.js';
import { VirtualStream } from './typedrequest.classes.virtualstream.js';
import { TypedResponseError } from './typedrequest.classes.typedresponseerror.js';
import { TypedRouter } from './typedrequest.classes.typedrouter.js';
import { TypedTarget } from './typedrequest.classes.typedtarget.js';
import { VirtualStream } from './classes.virtualstream.js';
import { TypedResponseError } from './classes.typedresponseerror.js';
import { TypedRouter } from './classes.typedrouter.js';
import { TypedTarget } from './classes.typedtarget.js';
const webrequestInstance = new plugins.webrequest.WebRequest();
@ -79,7 +79,7 @@ export class TypedRequest<T extends plugins.typedRequestInterfaces.ITypedRequest
}
if (payloadReceiving.error) {
console.error(
`Got an error ${payloadReceiving.error.text} with data ${JSON.stringify(
`method: >>${this.method}<< got an ERROR: "${payloadReceiving.error.text}" with data ${JSON.stringify(
payloadReceiving.error.data,
null,
2

View File

@ -1,8 +1,8 @@
import * as plugins from './plugins.js';
import { VirtualStream } from './typedrequest.classes.virtualstream.js';
import { VirtualStream } from './classes.virtualstream.js';
import { TypedHandler } from './typedrequest.classes.typedhandler.js';
import { TypedRequest } from './typedrequest.classes.typedrequest.js';
import { TypedHandler } from './classes.typedhandler.js';
import { TypedRequest } from './classes.typedrequest.js';
/**
* A typed router decides on which typed handler to call based on the method

View File

@ -1,4 +1,4 @@
import { TypedRouter } from './typedrequest.classes.typedrouter.js';
import { TypedRouter } from './classes.typedrouter.js';
import * as plugins from './plugins.js';
export type IPostMethod = (

13
ts/classes.typedtools.ts Normal file
View File

@ -0,0 +1,13 @@
import { TypedResponseError } from './classes.typedresponseerror.js';
import * as plugins from './plugins.js';
export class TypedTools {
public async passGuards<T = any>(guardsArg: plugins.smartguard.Guard<T>[], dataArg: T) {
const guardSet = new plugins.smartguard.GuardSet<T>(guardsArg);
const guardResult = await guardSet.allGuardsPass(dataArg);
if (!guardResult) {
const failedHint = await guardSet.getFailedHint(dataArg);
throw new TypedResponseError(`guard failed: ${failedHint}`, { failedHint });
}
}
}

View File

@ -1,5 +1,5 @@
import * as plugins from './plugins.js';
import type { TypedRouter } from './typedrequest.classes.typedrouter.js';
import { TypedRouter } from './classes.typedrouter.js';
export interface ICommFunctions {
sendMethod?: (
@ -15,7 +15,7 @@ export interface ICommFunctions {
* 3. It has a Readable and Writable side.
* 4. The Writable side is Readable on the other side and vice versa.
*/
export class VirtualStream<T = ArrayBufferLike> implements plugins.typedRequestInterfaces.IVirtualStream<T> {
export class VirtualStream<T = Uint8Array> implements plugins.typedRequestInterfaces.IVirtualStream<T> {
// STATIC
public static encodePayloadForNetwork(
objectPayload: any,
@ -79,7 +79,11 @@ export class VirtualStream<T = ArrayBufferLike> implements plugins.typedRequestI
}
public static decodePayloadFromNetwork(objectPayload: any, commFunctions: ICommFunctions): any {
if (plugins.smartbuffer.isBufferLike(objectPayload)) {
if (
plugins.smartbuffer.isBufferLike(objectPayload)
|| objectPayload instanceof TypedRouter
) {
return objectPayload;
}
if (objectPayload !== null && typeof objectPayload === 'object') {
@ -158,7 +162,7 @@ export class VirtualStream<T = ArrayBufferLike> implements plugins.typedRequestI
cycle: 'request',
mainPurpose: 'feedback',
next: this.sendBackpressuredArray.data.length > 0,
backpressure: this.receiveBackpressuredArray.checkSpaceAvailable(),
backpressure: !this.receiveBackpressuredArray.checkSpaceAvailable(),
},
response: null,
}).catch(() => {
@ -174,6 +178,12 @@ export class VirtualStream<T = ArrayBufferLike> implements plugins.typedRequestI
// do work loop
while (this.sendBackpressuredArray.data.length > 0 || otherSideHasNext) {
if (otherSideIsBackpressured) {
while (otherSideIsBackpressured) {
await plugins.smartdelay.delayFor(50);
await getFeedback();
}
}
let dataArg: typeof this.sendBackpressuredArray.data[0];
if (this.sendBackpressuredArray.data.length > 0) {
dataArg = this.sendBackpressuredArray.shift();
@ -200,7 +210,8 @@ export class VirtualStream<T = ArrayBufferLike> implements plugins.typedRequestI
if (streamTr && streamTr.response && streamTr.response.chunkData) {
this.receiveBackpressuredArray.push(streamTr.response.chunkData);
}
thisSideIsBackpressured = this.receiveBackpressuredArray.checkSpaceAvailable();
otherSideIsBackpressured = streamTr && streamTr.response && streamTr.response.backpressure;
thisSideIsBackpressured = !this.receiveBackpressuredArray.checkSpaceAvailable();
// lets care about looping
otherSideHasNext = streamTr && streamTr.response && streamTr.response.next;
@ -231,7 +242,7 @@ export class VirtualStream<T = ArrayBufferLike> implements plugins.typedRequestI
mainPurpose: 'keepAlive',
keepAlive: this.keepAlive,
next: this.sendBackpressuredArray.data.length > 0,
backpressure: this.receiveBackpressuredArray.checkSpaceAvailable(),
backpressure: !this.receiveBackpressuredArray.checkSpaceAvailable(),
};
}
@ -243,7 +254,7 @@ export class VirtualStream<T = ArrayBufferLike> implements plugins.typedRequestI
cycle: 'response',
mainPurpose: 'feedback',
next: this.sendBackpressuredArray.data.length > 0,
backpressure: this.receiveBackpressuredArray.checkSpaceAvailable(),
backpressure: !this.receiveBackpressuredArray.checkSpaceAvailable(),
};
}
@ -291,10 +302,14 @@ export class VirtualStream<T = ArrayBufferLike> implements plugins.typedRequestI
*/
private async startKeepAliveLoop() {
// initially wait for a second
if (this.side === 'responding') {
return;
}
await plugins.smartdelay.delayFor(0);
console.log(`starting keepalive loop on side ${this.side}`);
let counter = 0;
keepAliveLoop: while (this.keepAlive) {
const triggerResult = await this.triggerKeepAlive();
await this.triggerKeepAlive();
await plugins.smartdelay.delayFor(1000);
}
await plugins.smartdelay.delayFor(1000);
@ -355,7 +370,7 @@ export class VirtualStream<T = ArrayBufferLike> implements plugins.typedRequestI
* reads from a Readable and sends it to the other side
* @param readableStreamArg
*/
public async readFromWebstream(readableStreamArg: ReadableStream<T>) {
public async readFromWebstream(readableStreamArg: ReadableStream<T>, closeAfterReading = true) {
const reader = readableStreamArg.getReader();
let streamIsDone = false;
while(!streamIsDone) {
@ -365,12 +380,19 @@ export class VirtualStream<T = ArrayBufferLike> implements plugins.typedRequestI
}
streamIsDone = done;
}
if (closeAfterReading) {
await this.close();
}
}
public async writeToWebstream(writableStreamArg: WritableStream<T>) {
const writer = writableStreamArg.getWriter();
while(this.keepAlive) {
while(this.keepAlive || this.receiveBackpressuredArray.checkHasItems()) {
await writer.write(await this.fetchData());
}
}
public async close() {
this.keepAlive = false;
}
}

View File

@ -1,6 +1,6 @@
export * from './typedrequest.classes.typedrequest.js';
export * from './typedrequest.classes.typedhandler.js';
export * from './typedrequest.classes.typedrouter.js';
export * from './typedrequest.classes.typedresponseerror.js';
export * from './typedrequest.classes.typedtarget.js';
export * from './typedrequest.classes.virtualstream.js';
export * from './classes.typedrequest.js';
export * from './classes.typedhandler.js';
export * from './classes.typedrouter.js';
export * from './classes.typedresponseerror.js';
export * from './classes.typedtarget.js';
export * from './classes.virtualstream.js';

View File

@ -8,8 +8,8 @@ import * as isounique from '@push.rocks/isounique';
import * as lik from '@push.rocks/lik';
import * as smartbuffer from '@push.rocks/smartbuffer';
import * as smartdelay from '@push.rocks/smartdelay';
import * as smartguard from '@push.rocks/smartguard';
import * as smartpromise from '@push.rocks/smartpromise';
import * as webrequest from '@push.rocks/webrequest';
export { isounique, lik, smartbuffer, smartdelay, smartpromise, webrequest };
export { isounique, lik, smartbuffer, smartdelay, smartguard, smartpromise, webrequest };