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

Creating better file content streaming RPC methods #799

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/client/ClientService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,14 @@ class ClientService {
keepAliveTimeoutTime,
},
logger: this.logger.getChild(WebSocketServer.name),
codeToReason: (type, code) => {
console.log(code);
return new Error(`webserver: ${type}: ${code}`);
},
reasonToCode: (_, reason) => {
console.error('webserver:', reason);
return 0;
}
});
}

Expand Down
11 changes: 2 additions & 9 deletions src/client/callers/vaultsSecretsEdit.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,5 @@
import type { HandlerTypes } from '@matrixai/rpc';
import type VaultsSecretsEdit from '../handlers/VaultsSecretsEdit';
import { UnaryCaller } from '@matrixai/rpc';
import { RawCaller } from '@matrixai/rpc';

type CallerTypes = HandlerTypes<VaultsSecretsEdit>;

const vaultsSecretsEdit = new UnaryCaller<
CallerTypes['input'],
CallerTypes['output']
>();
const vaultsSecretsEdit = new RawCaller();

export default vaultsSecretsEdit;
11 changes: 2 additions & 9 deletions src/client/callers/vaultsSecretsGet.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,5 @@
import type { HandlerTypes } from '@matrixai/rpc';
import type VaultsSecretsGet from '../handlers/VaultsSecretsGet';
import { UnaryCaller } from '@matrixai/rpc';
import { RawCaller } from '@matrixai/rpc';

type CallerTypes = HandlerTypes<VaultsSecretsGet>;

const vaultsSecretsGet = new UnaryCaller<
CallerTypes['input'],
CallerTypes['output']
>();
const vaultsSecretsGet = new RawCaller();

export default vaultsSecretsGet;
107 changes: 79 additions & 28 deletions src/client/handlers/VaultsSecretsEdit.ts
Original file line number Diff line number Diff line change
@@ -1,50 +1,101 @@
import type { DB } from '@matrixai/db';
import type {
ClientRPCRequestParams,
ClientRPCResponseResult,
SecretContentMessage,
SuccessMessage,
} from '../types';
import type VaultManager from '../../vaults/VaultManager';
import { UnaryHandler } from '@matrixai/rpc';
import { ReadableStream } from 'stream/web';
import { JSONObject, JSONRPCRequest, RawHandler } from '@matrixai/rpc';
import { validateSync } from '../../validation';
import { matchSync } from '../../utils';
import { fileTree } from '../../vaults';
import * as vaultsUtils from '../../vaults/utils';
import * as vaultsErrors from '../../vaults/errors';
import * as vaultOps from '../../vaults/VaultOps';
import * as validationErrors from '../../validation/errors';
import { ContentNode } from '@/vaults/types';

class VaultsSecretsEdit extends UnaryHandler<
{
vaultManager: VaultManager;
db: DB;
},
ClientRPCRequestParams<SecretContentMessage>,
ClientRPCResponseResult<SuccessMessage>
> {
class VaultsSecretsEdit extends RawHandler<{
vaultManager: VaultManager;
db: DB;
}> {
public handle = async (
input: ClientRPCRequestParams<SecretContentMessage>,
): Promise<ClientRPCResponseResult<SuccessMessage>> => {
input: [JSONRPCRequest, ReadableStream<Uint8Array>],
): Promise<[JSONObject, ReadableStream<Uint8Array>]> => {
const { vaultManager, db } = this.container;
const [headerMessage, secretContentStream] = input;
const params = headerMessage.params;

if (params == null) {
throw new validationErrors.ErrorParse('Input params cannot be undefined');
}

const {
nameOrId,
secretNames,
}: { nameOrId: string; secretNames: Array<string> } = validateSync(
(keyPath, value) => {
return matchSync(keyPath)(
[
['nameOrId'],
() => {
if (typeof value != 'string') {
throw new validationErrors.ErrorParse(
'Parameter must be of type string',
);
}
return value as string;
},
],
[
['secretNames'],
() => {
if (
!Array.isArray(value) ||
value.length === 0 ||
!value.every((v) => typeof v === 'string')
) {
throw new validationErrors.ErrorParse(
'Parameter must be a non-empty array of strings',
);
}
return value as Array<string>;
},
],
() => value,
);
},
{
nameOrId: params.nameOrId,
secretNames: params.secretNames,
},
);

const data: Array<ContentNode | Uint8Array> = [];
const dataStream = secretContentStream.pipeThrough(
fileTree.parserTransformStreamFactory(),
);
for await (const chunk of dataStream) data.push(chunk);
const secretContents = data
.filter((v) => v instanceof Uint8Array)
.map((v) => Buffer.from(v as Uint8Array).toString());

await db.withTransactionF(async (tran) => {
const vaultIdFromName = await vaultManager.getVaultId(
input.nameOrId,
tran,
);
const vaultId =
vaultIdFromName ?? vaultsUtils.decodeVaultId(input.nameOrId);
const vaultIdFromName = await vaultManager.getVaultId(nameOrId, tran);
const vaultId = vaultIdFromName ?? vaultsUtils.decodeVaultId(nameOrId);
if (vaultId == null) {
throw new vaultsErrors.ErrorVaultsVaultUndefined();
}
const secretContent = Buffer.from(input.secretContent, 'binary');

await vaultManager.withVaults(
[vaultId],
async (vault) => {
await vaultOps.updateSecret(vault, input.secretName, secretContent);
for (let i = 0; i < secretNames.length; i++) {
const name = secretNames[i];
const content = secretContents[i];
await vaultOps.updateSecret(vault, name, content);
}
},
tran,
);
});
return {
success: true,
};
return [{ success: true }, new ReadableStream()];
};
}

Expand Down
149 changes: 118 additions & 31 deletions src/client/handlers/VaultsSecretsGet.ts
Original file line number Diff line number Diff line change
@@ -1,49 +1,136 @@
import type { DB } from '@matrixai/db';
import type {
ClientRPCRequestParams,
ClientRPCResponseResult,
ContentMessage,
SecretIdentifierMessage,
} from '../types';
import type { JSONObject, JSONRPCRequest } from '@matrixai/rpc';
import type VaultManager from '../../vaults/VaultManager';
import { UnaryHandler } from '@matrixai/rpc';
import { ReadableStream } from 'stream/web';
import { RawHandler } from '@matrixai/rpc';
import { validateSync } from '../../validation';
import { matchSync } from '../../utils';
import { fileTree } from '../../vaults';
import * as vaultsUtils from '../../vaults/utils';
import * as vaultsErrors from '../../vaults/errors';
import * as vaultOps from '../../vaults/VaultOps';
import * as validationErrors from '../../validation/errors';
import * as utils from '../../utils';

class VaultsSecretsGet extends UnaryHandler<
{
vaultManager: VaultManager;
db: DB;
},
ClientRPCRequestParams<SecretIdentifierMessage>,
ClientRPCResponseResult<ContentMessage>
> {
class VaultsSecretsGet extends RawHandler<{
vaultManager: VaultManager;
db: DB;
}> {
public handle = async (
input: ClientRPCRequestParams<SecretIdentifierMessage>,
): Promise<ClientRPCResponseResult<ContentMessage>> => {
input: [JSONRPCRequest, ReadableStream<Uint8Array>],
): Promise<[JSONObject, ReadableStream<Uint8Array>]> => {
const { vaultManager, db } = this.container;
return await db.withTransactionF(async (tran) => {
const vaultIdFromName = await vaultManager.getVaultId(
input.nameOrId,
tran,
);
const vaultId =
vaultIdFromName ?? vaultsUtils.decodeVaultId(input.nameOrId);
const [headerMessage, inputStream] = input;
const params = headerMessage.params;
await inputStream.cancel();

if (params == null) {
throw new validationErrors.ErrorParse('Input params cannot be undefined');
}

const {
nameOrId,
secretNames,
}: { nameOrId: string; secretNames: Array<string> } = validateSync(
(keyPath, value) => {
return matchSync(keyPath)(
[
['nameOrId'],
() => {
if (typeof value != 'string') {
throw new validationErrors.ErrorParse(
'Parameter must be of type string',
);
}
return value as string;
},
],
[
['secretNames'],
() => {
if (
!Array.isArray(value) ||
value.length === 0 ||
!value.every((v) => typeof v === 'string')
) {
throw new validationErrors.ErrorParse(
'Parameter must be a non-empty array of strings',
);
}
return value as Array<string>;
},
],
() => value,
);
},
{
nameOrId: params.nameOrId,
secretNames: params.secretNames,
},
);
const testGen = db.withTransactionG(async function* (tran): AsyncGenerator<
Uint8Array,
void,
void
> {
const vaultIdFromName = await vaultManager.getVaultId(nameOrId, tran);
const vaultId = vaultIdFromName ?? vaultsUtils.decodeVaultId(nameOrId);
if (vaultId == null) {
throw new vaultsErrors.ErrorVaultsVaultUndefined();
}
const secretContent = await vaultManager.withVaults(
// Get secret contents
yield* vaultManager.withVaultsG(
[vaultId],
async (vault) => {
return await vaultOps.getSecret(vault, input.secretName);
(vault) => {
return vault.readG(async function* (fs): AsyncGenerator<
Uint8Array,
void,
void
> {
const contents = fileTree.serializerStreamFactory(fs, secretNames);
for await (const chunk of contents) yield chunk;
});
},
tran,
);
return {
secretContent: secretContent.toString('binary'),
};
});

try {
console.log(await testGen.next());
} catch (e) {
console.error(e);
} finally {
console.log('out of test block');
}

const secretContentsGen = db.withTransactionG(
async function* (tran): AsyncGenerator<Uint8Array, void, void> {
const vaultIdFromName = await vaultManager.getVaultId(nameOrId, tran);
const vaultId = vaultIdFromName ?? vaultsUtils.decodeVaultId(nameOrId);
if (vaultId == null) {
throw new vaultsErrors.ErrorVaultsVaultUndefined();
}
// Get secret contents
yield* vaultManager.withVaultsG(
[vaultId],
(vault) => {
return vault.readG(async function* (fs): AsyncGenerator<
Uint8Array,
void,
void
> {
const contents = fileTree.serializerStreamFactory(
fs,
secretNames,
);
for await (const chunk of contents) yield chunk;
});
},
tran,
);
},
);

return [{}, utils.asyncGeneratorToStream(secretContentsGen)];
};
}

Expand Down
31 changes: 31 additions & 0 deletions src/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import os from 'os';
import process from 'process';
import path from 'path';
import nodesEvents from 'events';
import { ReadableStream } from 'stream/web';
import lexi from 'lexicographic-integer';
import { PromiseCancellable } from '@matrixai/async-cancellable';
import { timedCancellable } from '@matrixai/contexts/dist/functions';
Expand Down Expand Up @@ -541,6 +542,34 @@ function setMaxListeners(
nodesEvents.setMaxListeners(limit, target);
}

async function* streamToAsyncGenerator<T>(
stream: ReadableStream<T>,
): AsyncGenerator<T, void, unknown> {
for await (const chunk of stream) {
yield chunk;
}
}

function asyncGeneratorToStream<T>(
generator: AsyncGenerator<T, void, unknown>,
): ReadableStream<T> {
return new ReadableStream({
pull: async (controller) => {
try {
const { value, done } = await generator.next();
if (done) controller.close();
else controller.enqueue(value);
} catch (e) {
console.error("from generator, ", e);
controller.error(e);
}
},
cancel: async (reason) => {
await generator.throw(reason).catch(() => {});
},
});
}

export {
AsyncFunction,
GeneratorFunction,
Expand Down Expand Up @@ -581,4 +610,6 @@ export {
isBufferSource,
yieldMicro,
setMaxListeners,
streamToAsyncGenerator,
asyncGeneratorToStream,
Comment on lines +613 to +614
Copy link
Member

Choose a reason for hiding this comment

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

I feel like these should really be in its own utility system.

Also don't we already have ixjs combinators available? Doesn't that already do this? Usually that library has these features.

Copy link
Member

Choose a reason for hiding this comment

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

See the ix library 5.0.0. I feel like there would already be some combinator for async iterator to web streams.

};
Loading