Skip to content

Commit

Permalink
migrated to recent updates
Browse files Browse the repository at this point in the history
  • Loading branch information
andorsk committed Sep 27, 2023
1 parent d1126c8 commit 3547c74
Show file tree
Hide file tree
Showing 4 changed files with 124 additions and 66 deletions.
27 changes: 14 additions & 13 deletions src/subscription-manager.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import type { Dwn, SubscriptionFilter } from '@tbd54566975/dwn-sdk-js';
import type { EventMessage, PermissionsGrant } from '@tbd54566975/dwn-sdk-js';
import type {
MessageStore,
SubscriptionRequestReply,
} from '@tbd54566975/dwn-sdk-js';

import type { JsonRpcSuccessResponse } from './lib/json-rpc.js';
import type { MessageStore } from '@tbd54566975/dwn-sdk-js';
import { SubscriptionRequest } from '@tbd54566975/dwn-sdk-js';
import type { SubscriptionRequestReply } from '@tbd54566975/dwn-sdk-js';
import type WebSocket from 'ws';
import { WebSocketServer } from 'ws';
import { v4 as uuidv4 } from 'uuid';
Expand Down Expand Up @@ -34,8 +32,8 @@ export type RegisterSubscriptionRequest = {
from: string;
socket: WebSocket;
filters?: SubscriptionFilter[];
permissionGrant: PermissionsGrant;
subscriptionRequestMessage: SubscriptionRequest;
permissionGrant?: PermissionsGrant;
request: SubscriptionRequest;
};

export type RegisterSubscriptionReply = {
Expand All @@ -46,8 +44,7 @@ export type RegisterSubscriptionReply = {
export type defaultSubscriptionChannel = 'event';

export type SubscriptionManagerOptions = {
subscriptionChannel: string;
wss: WebSocketServer;
wss?: WebSocketServer;
dwn: Dwn;
messageStore: MessageStore;
tenant: string;
Expand Down Expand Up @@ -116,8 +113,13 @@ export class SubscriptionManager {
data: any,
): Promise<RegisterSubscriptionReply> {
// parse message
const req = SubscriptionRequest.parse(data);
return await this.subscribe(req, socket);
const req = await SubscriptionRequest.parse(data);

return await this.subscribe({
request: req,
socket: socket,
from: req.author,
});
}

createJSONRPCEvent(e: EventMessage): JsonRpcSuccessResponse {
Expand All @@ -130,11 +132,10 @@ export class SubscriptionManager {

async subscribe(
req: RegisterSubscriptionRequest,
socket: WebSocket,
): Promise<RegisterSubscriptionReply> {
const subscriptionReply = await this.dwn.handleSubscriptionRequest(
this.tenant,
req.subscriptionRequestMessage,
req.request.message,
);
if (subscriptionReply.status.code !== 200) {
return { reply: subscriptionReply };
Expand All @@ -146,7 +147,7 @@ export class SubscriptionManager {
async (e: EventMessage): Promise<void> => {
const jsonRpcResponse = this.createJSONRPCEvent(e);
const str = JSON.stringify(jsonRpcResponse);
return socket.send(Buffer.from(str));
return req.socket.send(Buffer.from(str));
},
);
}
Expand Down
42 changes: 20 additions & 22 deletions tests/http-api.spec.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,39 @@
// node.js 18 and earlier, needs globalThis.crypto polyfill
import { webcrypto } from 'node:crypto';

if (!globalThis.crypto) {
// @ts-ignore
globalThis.crypto = webcrypto;
}

import type { Server } from 'http';
import type {
JsonRpcErrorResponse,
JsonRpcResponse,
} from '../src/lib/json-rpc.js';

import fetch from 'node-fetch';
import request from 'supertest';

import { expect } from 'chai';
import { HttpApi } from '../src/http-api.js';
import { v4 as uuidv4 } from 'uuid';
import {
Cid,
DataStream,
RecordsQuery,
RecordsRead,
} from '@tbd54566975/dwn-sdk-js';
import { clear as clearDwn, dwn } from './test-dwn.js';
import {
createJsonRpcRequest,
JsonRpcErrorCodes,
createJsonRpcRequest,
} from '../src/lib/json-rpc.js';
import type {
JsonRpcErrorResponse,
JsonRpcResponse,
} from '../src/lib/json-rpc.js';
import { clear as clearDwn, dwn } from './test-dwn.js';
import {
createProfile,
createRecordsWriteMessage,
getFileAsReadStream,
streamHttpRequest,
} from './utils.js';

import { HttpApi } from '../src/http-api.js';
import type { Server } from 'http';
import { expect } from 'chai';
import fetch from 'node-fetch';
import request from 'supertest';
import { v4 as uuidv4 } from 'uuid';
// node.js 18 and earlier, needs globalThis.crypto polyfill
import { webcrypto } from 'node:crypto';

if (!globalThis.crypto) {
// @ts-ignore
globalThis.crypto = webcrypto;
}

describe('http api', function () {
let httpApi: HttpApi;
let server: Server;
Expand Down
102 changes: 84 additions & 18 deletions tests/subscription-manager.spec.ts
Original file line number Diff line number Diff line change
@@ -1,44 +1,110 @@
import { assert } from 'chai';
import { createProfile } from './utils.js';
import http from 'node:http';
import { WebSocket, type WebSocketServer } from 'ws';

import {
DataStoreLevel,
DidKeyResolver,
Dwn,
EventLogLevel,
MessageStoreLevel,
SubscriptionRequest,
} from '@tbd54566975/dwn-sdk-js';

import { Jws } from '@tbd54566975/dwn-sdk-js';
import type { SubscriptionController } from '../src/subscription-manager.js';
import { SubscriptionManager } from '../src/subscription-manager.js';
import { assert } from 'chai';
import { createProfile } from './utils.js';
import type { Profile } from './utils.js';
import { WsApi } from '../src/ws-api.js';

describe('Subscription Manager Test', () => {
describe('Subscription Manager Test', async () => {
let subscriptionManager: SubscriptionController;
let wsServer: WebSocketServer;
let server: http.Server;
let dataStore: DataStoreLevel;
let eventLog: EventLogLevel;
let messageStore: MessageStoreLevel;
let alice: Profile;
let dwn: Dwn;
let socket: WebSocket;

// important to follow the `before` and `after` pattern to initialize and clean the stores in tests
// so that different test suites can reuse the same backend store for testing
before(async () => {
subscriptionManager = new SubscriptionManager({});
// Setup data stores...
dataStore = new DataStoreLevel({
blockstoreLocation: 'data/DATASTORE',
});
eventLog = new EventLogLevel({ location: 'data/EVENTLOG' });
messageStore = new MessageStoreLevel({
blockstoreLocation: 'data/MESSAGESTORE',
indexLocation: 'data/INDEX',
});

// create profile
alice = await createProfile();
// create Dwn
dwn = await Dwn.create({ eventLog, dataStore, messageStore });

// create listeners...
server = http.createServer();
server.listen(9002, '127.0.0.1');
const wsApi = new WsApi(server, dwn);
wsServer = wsApi.start();

// create subscription manager...
subscriptionManager = new SubscriptionManager({
dwn: dwn,
messageStore: messageStore,
tenant: alice.did,
wss: wsServer,
});
return;
});

// before each, clear the subscriptions
beforeEach(async () => {
subscriptionManager.clear();
await dataStore.clear();
await eventLog.clear();
await messageStore.clear();
});

// close at the end
after(async () => {
await subscriptionManager.close();
wsServer.close();
server.close();
server.closeAllConnections();
socket.close();
});

it('test subscription manager registration', async () => {
try {
const alice = await createProfile();
const signer = await DidKeyResolver.generate();

// create a subscription request
const req = await SubscriptionRequest.create({
filter: {
eventType: EventType.Operation,
},
authorizationSignatureInput: Jws.createSignatureInput(alice),
signer: Jws.createSigner(signer),
});
const subscription = await subscriptionManager.subscribe({
from: alice.did,
subscriptionRequestMessage: req,
permissionGrant: 'asdf',
});
assert.isDefined(subscription.reply);
assert.isDefined(subscription.subscriptionId);

// setup a socket connection to wsServer
const socket = new WebSocket(wsServer.address.toString());
socket.onopen = async (): Promise<void> => {
console.log('sending req', req);
// send a subscription request
// const subscription = await subscriptionManager.subscribe({
// from: alice.did,
// subscriptionRequestMessage: req,
// permissionGrant: 'asdf',
// });
socket.send('subscription request');
return;
};

socket.onmessage = (event): Promise<void> => {
console.log('got message', event);
return;
};
} catch (error) {
assert.fail(error, undefined, 'failed to register subscription');
}
Expand Down
19 changes: 6 additions & 13 deletions tests/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ import {
Cid,
DataStream,
DidKeyResolver,
PrivateKeySigner,
RecordsWrite,
SubscriptionRequest,
} from '@tbd54566975/dwn-sdk-js';
import { Jws } from '@tbd54566975/dwn-sdk-js';

// __filename and __dirname are not defined in ES module scope
const __filename = fileURLToPath(import.meta.url);
Expand All @@ -32,18 +32,11 @@ export type Profile = {

export async function createProfile(): Promise<Profile> {
const { did, keyPair, keyId } = await DidKeyResolver.generate();

// signer is required by all dwn message classes. it's used to sign messages
const signer = new PrivateKeySigner({
privateJwk: keyPair.privateJwk,
algorithm: keyPair.privateJwk.alg,
keyId: `${did}#${keyId}`,
});

const signer = Jws.createSigner({ keyPair, keyId });
return {
did,
keyPair,
signer,
did: did,
keyPair: keyPair,
signer: signer,
};
}

Expand Down Expand Up @@ -76,7 +69,7 @@ export async function createSubscriptionRequest(
): Promise<SubscriptionRequest> {
console.log(overrides);
const subscriptionRequest = await SubscriptionRequest.create({
authorizationSignatureInput: signer.signatureInput,
signer: signer.signer,
});
return subscriptionRequest;
}
Expand Down

0 comments on commit 3547c74

Please sign in to comment.