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

Uses SavedObjectsClient for Short URL Lookup #12787

Merged
merged 1 commit into from
Jul 12, 2017
Merged
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
103 changes: 103 additions & 0 deletions src/server/http/__tests__/short_url_lookup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import expect from 'expect.js';
import sinon from 'sinon';
import shortUrlLookupProvider from '../short_url_lookup';

describe('shortUrlLookupProvider', () => {
const ID = 'bf00ad16941fc51420f91a93428b27a0';
const TYPE = 'url';
const URL = 'http://elastic.co';
const server = { log: sinon.stub() };
const sandbox = sinon.sandbox.create();

let savedObjectsClient;
let req;
let shortUrl;

beforeEach(() => {
savedObjectsClient = {
get: sandbox.stub(),
create: sandbox.stub().returns(Promise.resolve({ id: ID })),
update: sandbox.stub()
};

req = { getSavedObjectsClient: () => savedObjectsClient };
shortUrl = shortUrlLookupProvider(server);
});

afterEach(() => {
sandbox.restore();
});

describe('generateUrlId', () => {
it('returns the document id', async () => {
const id = await shortUrl.generateUrlId(URL, req);
expect(id).to.eql(ID);
});

it('provides correct arguments to savedObjectsClient', async () => {
await shortUrl.generateUrlId(URL, req);

sinon.assert.calledOnce(savedObjectsClient.create);
const [type, attributes, options] = savedObjectsClient.create.getCall(0).args;

expect(type).to.eql(TYPE);
expect(attributes).to.only.have.keys('url', 'accessCount', 'createDate', 'accessDate');
expect(attributes.url).to.eql(URL);
expect(options.id).to.eql(ID);
});

it('passes persists attributes', async () => {
await shortUrl.generateUrlId(URL, req);

sinon.assert.calledOnce(savedObjectsClient.create);
const [type, attributes] = savedObjectsClient.create.getCall(0).args;

expect(type).to.eql(TYPE);
expect(attributes).to.only.have.keys('url', 'accessCount', 'createDate', 'accessDate');
expect(attributes.url).to.eql(URL);
});

it('gracefully handles version conflict', async () => {
const error = new Error('version conflict');
error.data = { type: 'version_conflict_engine_exception' };
savedObjectsClient.create.throws(error);

const id = await shortUrl.generateUrlId(URL, req);
expect(id).to.eql(ID);
});
});

describe('getUrl', () => {
beforeEach(() => {
const attributes = { accessCount: 2, url: URL };
savedObjectsClient.get.returns({ id: ID, attributes });
});

it('provides the ID to savedObjectsClient', async () => {
await shortUrl.getUrl(ID, req);

sinon.assert.calledOnce(savedObjectsClient.get);
const [type, id] = savedObjectsClient.get.getCall(0).args;

expect(type).to.eql(TYPE);
expect(id).to.eql(ID);
});

it('returns the url', async () => {
const response = await shortUrl.getUrl(ID, req);
expect(response).to.eql(URL);
});

it('increments accessCount', async () => {
await shortUrl.getUrl(ID, req);

sinon.assert.calledOnce(savedObjectsClient.update);
const [type, id, attributes] = savedObjectsClient.update.getCall(0).args;

expect(type).to.eql(TYPE);
expect(id).to.eql(ID);
expect(attributes).to.only.have.keys('accessCount', 'accessDate');
expect(attributes.accessCount).to.eql(3);
});
});
});
105 changes: 26 additions & 79 deletions src/server/http/short_url_lookup.js
Original file line number Diff line number Diff line change
@@ -1,100 +1,47 @@
import crypto from 'crypto';
import { get } from 'lodash';

export default function (server) {
async function updateMetadata(urlId, urlDoc, req) {
const { callWithRequest } = server.plugins.elasticsearch.getCluster('admin');
const kibanaIndex = server.config().get('kibana.index');

async function updateMetadata(doc, req) {
try {
await callWithRequest(req, 'update', {
index: kibanaIndex,
type: 'url',
id: urlId,
body: {
doc: {
'accessDate': new Date(),
'accessCount': urlDoc._source.accessCount + 1
}
}
await req.getSavedObjectsClient().update('url', doc.id, {
accessDate: new Date(),
accessCount: get(doc, 'attributes.accessCount', 0) + 1
});
} catch (err) {
server.log('Warning: Error updating url metadata', err);
//swallow errors. It isn't critical if there is no update.
}
}

async function getUrlDoc(urlId, req) {
const urlDoc = await new Promise(resolve => {
const { callWithRequest } = server.plugins.elasticsearch.getCluster('admin');
const kibanaIndex = server.config().get('kibana.index');

callWithRequest(req, 'get', {
index: kibanaIndex,
type: 'url',
id: urlId
})
.then(response => {
resolve(response);
})
.catch(() => {
resolve();
});
});

return urlDoc;
}

async function createUrlDoc(url, urlId, req) {
const newUrlId = await new Promise((resolve, reject) => {
const { callWithRequest } = server.plugins.elasticsearch.getCluster('admin');
const kibanaIndex = server.config().get('kibana.index');
return {
async generateUrlId(url, req) {
const id = crypto.createHash('md5').update(url).digest('hex');

callWithRequest(req, 'index', {
index: kibanaIndex,
type: 'url',
id: urlId,
body: {
try {
const doc = await req.getSavedObjectsClient().create('url', {
url,
'accessCount': 0,
'createDate': new Date(),
'accessDate': new Date()
accessCount: 0,
createDate: new Date(),
accessDate: new Date()
}, { id });

return doc.id;
} catch(e) {
if (get(e, 'data.type') === 'version_conflict_engine_exception') {
return id;
}
})
.then(response => {
resolve(response._id);
})
.catch(err => {
reject(err);
});
});

return newUrlId;
}

function createUrlId(url) {
const urlId = crypto.createHash('md5')
.update(url)
.digest('hex');

return urlId;
}

return {
async generateUrlId(url, req) {
const urlId = createUrlId(url);
const urlDoc = await getUrlDoc(urlId, req);
if (urlDoc) return urlId;

return createUrlDoc(url, urlId, req);
throw e;
}
},
async getUrl(urlId, req) {
try {
const urlDoc = await getUrlDoc(urlId, req);
if (!urlDoc) throw new Error('Requested shortened url does not exist in kibana index');

updateMetadata(urlId, urlDoc, req);
async getUrl(id, req) {
try {
const doc = await req.getSavedObjectsClient().get('url', id);
updateMetadata(doc, req);

return urlDoc._source.url;
return doc.attributes.url;
} catch (err) {
return '/';
}
Expand Down