Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fixes #20 - Ensure that HTTP Transport does not leak the HTTP Respons…
Browse files Browse the repository at this point in the history
…e wrapper

Signed-off-by: Frank Hinek <frankhinek@users.noreply.github.com>
frankhinek committed Apr 14, 2023
1 parent bf3f0b2 commit 86f9ecb
Showing 6 changed files with 60 additions and 60 deletions.
8 changes: 3 additions & 5 deletions examples/simple-agent/.gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# Agent Specific

BLOCKSTORE/
DATASTORE/
INDEX/
DATASTORE-*
INDEX-*
MESSAGESTORE-*
4 changes: 2 additions & 2 deletions examples/simple-agent/src/index.js
Original file line number Diff line number Diff line change
@@ -20,10 +20,10 @@ router.post('/dwn', async (ctx, _next) => {
try {
const response = await receiveHttp(ctx);

// Normalize DWN MessageReply and HTTP Reponse
// Normalize DWN MessageReply and HTTP Reponse messages
ctx.body = 'entries' in response ? { entries: response.entries } : response.body;
ctx.status = response?.status?.code ?? response?.status;
ctx.statusText = response?.status?.detail ?? response?.statusText;
ctx.body = 'entries' in response ? { entries: response.entries } : response.body;
}
catch(err) {
console.error(err);
14 changes: 13 additions & 1 deletion examples/simple-agent/src/utils.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,22 @@
import getRawBody from 'raw-body';
import { DataStoreLevel, Dwn, MessageStoreLevel } from '@tbd54566975/dwn-sdk-js';
import { Web5 } from '@tbd54566975/web5';
import fs from 'node:fs';
import mkdirp from 'mkdirp';
import { createRequire } from 'node:module';

const web5 = new Web5();
// Use custom names for the block, message, and data stores to make it possible to launch multiple simple agents
// in the same directory. If you don't do this, you will get LevelDB lock errors.
const port = await getPort(process.argv);
const dataStore = new DataStoreLevel({ blockstoreLocation: `DATASTORE-${port}` });
const messageStore = new MessageStoreLevel({
blockstoreLocation : `MESSAGESTORE-${port}`,
indexLocation : `INDEX-${port}`,
});

const dwnNode = await Dwn.create({ messageStore, dataStore });

const web5 = new Web5({ dwn: { node: dwnNode }});

const etcPath = './etc';
const didStoragePath = `${etcPath}/did.json`;
44 changes: 18 additions & 26 deletions examples/test-dashboard/desktop-agent.html
Original file line number Diff line number Diff line change
@@ -467,14 +467,6 @@
});
});

async function logConsole(obj, message = '') {
if (obj instanceof Response) {
console.log(message, await obj.json());
} else {
console.log(message, obj);
}
}

function agentConnected() {
if (!isAuthorized) {
alert('CONNECT or RECONNECT before sending messages.');
@@ -494,7 +486,7 @@
}
}
});
logConsole(response, 'QUERY:');
console.log(response);
});


@@ -509,7 +501,7 @@
}
}
});
logConsole(response);
console.log(response);
});


@@ -524,7 +516,7 @@
}
}
});
logConsole(response);
console.log(response);
});


@@ -539,7 +531,7 @@
}
}
});
logConsole(response);
console.log(response);
});

/* RECORDS READ */
@@ -582,7 +574,7 @@
}
})).json()

logConsole(response);
console.log(response);

const entry = response?.entries?.[0];
if (entry) {
@@ -601,7 +593,7 @@
recordId: read_by_id.value
}
});
logConsole(response, 'QUERY:');
console.log(response);
});

/* END RECORDS READ */
@@ -615,7 +607,7 @@
schema: write_text_schema.value,
}
});
logConsole(response);
console.log(response);
});


@@ -628,7 +620,7 @@
schema: write_json_schema.value,
}
});
logConsole(response);
console.log(response);
});


@@ -646,7 +638,7 @@
dataFormat: 'application/octet-stream'
}
});
logConsole(response);
console.log(response);
} else {
alert('No image file selected!');
}
@@ -667,7 +659,7 @@
dataFormat: write_image_type_data_format.value
}
});
logConsole(response);
console.log(response);
} else {
alert('No image file selected!');
}
@@ -680,7 +672,7 @@
recordId: delete_record_id.value
}
});
logConsole(response);
console.log(response);
});

configure_protocol_definition.value = JSON.stringify(
@@ -704,7 +696,7 @@
definition: JSON.parse(configure_protocol_definition.value)
}
});
logConsole(response);
console.log(response);
});

query_protocol_button.addEventListener('click', async event => {
@@ -717,7 +709,7 @@
}
}
});
logConsole(response);
console.log(response);
});

/**
@@ -756,7 +748,7 @@
// schema: 'foo/bar',
// }
// });
// logConsole(response);
// console.log(response);
alert('TEST NOT YET IMPLEMENTED');
});

@@ -769,7 +761,7 @@
schema: 'foo/bar'
}
});
logConsole(response);
console.log(response);
});

write_alice_to_bob_local_btn.addEventListener('click', async event => {
@@ -781,7 +773,7 @@
// schema: 'foo/bar',
// }
// });
// logConsole(response);
// console.log(response);
alert('TEST NOT YET IMPLEMENTED');
});

@@ -795,7 +787,7 @@
schema: 'test/post'
}
});
logConsole(response);
console.log(response);
});

query_alice_to_bob_remote_btn.addEventListener('click', async event => {
@@ -809,7 +801,7 @@
}
}
});
logConsole(response);
console.log(response);
});

</script>
33 changes: 16 additions & 17 deletions examples/test-dashboard/simple-agent.html
Original file line number Diff line number Diff line change
@@ -182,8 +182,7 @@ <h2>Read Records</h2>
schema: 'test/post',
}
});
const responseJSON = await logConsole(response);
if (responseJSON.status.code === 202) {
if (response.status.code === 202) {
write_text_result.textContent = 'Success';
write_text_result.classList.add('green');
} else {
@@ -204,9 +203,8 @@ <h2>Read Records</h2>
}
}
});
const responseJSON = await logConsole(response);
query_text_data.textContent = '';
for (let entry of responseJSON.entries) {
for (let entry of response.entries) {
const recordId = document.createElement('span');
recordId.classList.add('recordId');
recordId.textContent = `ID: ${entry.recordId}`;
@@ -258,7 +256,20 @@ <h2>Read Records</h2>
dataFormat: 'application/json'
}
});
logConsole(response, 'WRITE RESPONSE:');
console.log('Target bobDid write response:', response);

// Write a JSON record to the remote DWN.
response = await web5.dwn.records.query(bobDid, {
author: myDid.id,
message: {
filter: {
protocol: 'test',
schema: 'test/post',
dataFormat: 'application/json'
}
}
});
console.log('Target bobDid query response:', response);

// Convenience functions to decode data returned by queries
function base64UrlToString(encodedData) {
@@ -268,18 +279,6 @@ <h2>Read Records</h2>
function base64UrlToObject(encodedData) {
return web5.dwn.SDK.Encoder.base64UrlToObject(encodedData);
}

async function logConsole(obj, message = '') {
let result;
if (obj instanceof Response) {
result = await obj.json();
console.log(message, result);
} else {
result = obj;
console.log(message, result);
}
return result;
}
</script>
</body>

17 changes: 8 additions & 9 deletions src/transport/HTTPTransport.js
Original file line number Diff line number Diff line change
@@ -28,7 +28,7 @@ class HTTPTransport extends Transport {
}

async send(endpoint, request) { // override
return fetch(endpoint, {
const response = await fetch(endpoint, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
@@ -41,14 +41,13 @@ class HTTPTransport extends Transport {
'Content-Type': 'application/octet-stream',
},
body: request.data,
})
.then((response) => {
// Only resolve if response was successful (status of 200-299)
if (response.ok) {
return response;
}
return Promise.reject(response);
});
});

if (!response.ok) {
throw new Error(`Fetch failed with status ${response.status}`);
}

return await response.json();
}
}

0 comments on commit 86f9ecb

Please sign in to comment.