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

chore: move npm code #379

Merged
merged 8 commits into from
Aug 6, 2019
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
10 changes: 5 additions & 5 deletions src/__tests__/typescript.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { getTypeScriptSupport } from '../typescriptSupport';
jest.mock('../npm');
jest.mock('../unpkg');
import { validatePackageExists } from '../npm';
import * as npm from '../npm/index.js';
import { fileExistsInUnpkg } from '../unpkg.js';

describe('getTypeScriptSupport()', () => {
Expand All @@ -16,7 +16,7 @@ describe('getTypeScriptSupport()', () => {

describe('without types/typings', () => {
it('Checks for @types/[name]', async () => {
validatePackageExists.mockResolvedValue(true);
npm.validatePackageExists.mockResolvedValue(true);
const atTypesSupport = await getTypeScriptSupport({
name: 'my-lib',
types: { ts: false },
Expand All @@ -30,7 +30,7 @@ describe('getTypeScriptSupport()', () => {
});

it('Checks for @types/[scope__name]', async () => {
validatePackageExists.mockResolvedValue(true);
npm.validatePackageExists.mockResolvedValue(true);
const atTypesSupport = await getTypeScriptSupport({
name: '@my-scope/my-lib',
types: { ts: false },
Expand All @@ -44,7 +44,7 @@ describe('getTypeScriptSupport()', () => {
});

it('Checks for a d.ts resolved version of main ', async () => {
validatePackageExists.mockResolvedValue(false);
npm.validatePackageExists.mockResolvedValue(false);
fileExistsInUnpkg.mockResolvedValue(true);

const typesSupport = await getTypeScriptSupport({
Expand All @@ -55,7 +55,7 @@ describe('getTypeScriptSupport()', () => {
});

it('Handles not having any possible TS types', async () => {
validatePackageExists.mockResolvedValue(false);
npm.validatePackageExists.mockResolvedValue(false);
fileExistsInUnpkg.mockResolvedValue(false);

const typesSupport = await getTypeScriptSupport({
Expand Down
1 change: 0 additions & 1 deletion src/datadog.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,5 @@ const client = new StatsD({
log.error('[DATADOG ERROR]', error);
},
});
log.info('🐶 Datadog launched');

export default client;
73 changes: 26 additions & 47 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,17 @@
import PouchDB from 'pouchdb-http';
import ms from 'ms';
import cargo from 'async/cargo.js';
import queue from 'async/queue.js';
import createStateManager from './createStateManager.js';
import saveDocs from './saveDocs.js';
import createAlgoliaIndex from './createAlgoliaIndex.js';
import config from './config.js';
import * as npm from './npm.js';
import * as npm from './npm/index.js';
import log from './log.js';
import datadog from './datadog.js';
import { loadHits } from './jsDelivr.js';

log.info('🗿 npm ↔️ Algolia replication starts ⛷ 🐌 🛰');

const db = new PouchDB(config.npmRegistryEndpoint, {
ajax: {
timeout: ms('2.5m'), // default is 10s
},
});
const defaultOptions = {
include_docs: true, // eslint-disable-line camelcase
conflicts: false,
attachments: false,
};

let loopStart = Date.now();

const { index: mainIndex, client } = createAlgoliaIndex(config.indexName);
Expand Down Expand Up @@ -78,8 +66,7 @@ async function setSettings(index) {
}

async function logUpdateProgress(seq, nbChanges, emoji) {
const npmInfo = await npm.info();

const npmInfo = await npm.getInfo();
const ratePerSecond = nbChanges / ((Date.now() - loopStart) / 1000);
const remaining = ((npmInfo.seq - seq) / ratePerSecond) * 1000 || 0;
log.info(
Expand All @@ -94,7 +81,7 @@ async function logUpdateProgress(seq, nbChanges, emoji) {
}

async function logBootstrapProgress(offset, nbDocs) {
const { nbDocs: totalDocs } = await npm.info();
const { nbDocs: totalDocs } = await npm.getInfo();

const ratePerSecond = nbDocs / ((Date.now() - loopStart) / 1000);
log.info(
Expand All @@ -121,7 +108,7 @@ async function bootstrap(state) {

await loadHits();

const { seq, nbDocs: totalDocs } = await npm.info();
const { seq, nbDocs: totalDocs } = await npm.getInfo();
if (!state.bootstrapLastId) {
// Start from 0
log.info('⛷ Bootstrap: starting from the first doc');
Expand Down Expand Up @@ -160,21 +147,17 @@ async function bootstrapLoop(lastId) {
const start = Date.now();
log.info('loop()', '::', lastId);

const options =
lastId === undefined
? {}
: {
startkey: lastId,
skip: 1,
};

const start2 = Date.now();
const res = await db.allDocs({
...defaultOptions,
...options,
const options = {
limit: config.bootstrapConcurrency,
};
if (lastId) {
options.startkey = lastId;
options.skip = 1;
}

const res = await npm.findAll({
options,
});
datadog.timing('db.allDocs', Date.now() - start2);

if (res.rows.length <= 0) {
// Nothing left to process
Expand Down Expand Up @@ -220,21 +203,18 @@ async function replicate({ seq }) {
stage: 'replicate',
});

const { seq: npmSeqToReach } = await npm.info();
const { seq: npmSeqToReach } = await npm.getInfo();
let npmSeqReached = false;

return new Promise((resolve, reject) => {
const start2 = Date.now();
const changes = db.changes({
...defaultOptions,
const listener = npm.listenToChanges({
since: seq,
batch_size: config.replicateConcurrency, // eslint-disable-line camelcase
live: true,
return_docs: false, // eslint-disable-line camelcase
});
datadog.timing('db.changes', Date.now() - start2);

const q = cargo(async docs => {
const changesConsumer = cargo(async docs => {
datadog.increment('packages', docs.length);

try {
Expand All @@ -249,26 +229,26 @@ async function replicate({ seq }) {
}
}, config.replicateConcurrency);

changes.on('change', async change => {
listener.on('change', async change => {
if (change.deleted === true) {
await mainIndex.deleteObject(change.id);
log.info(`🐌 Deleted ${change.id}`);
}

q.push(change, err => {
changesConsumer.push(change, err => {
if (err) {
reject(err);
}
});

if (change.seq >= npmSeqToReach) {
npmSeqReached = true;
changes.cancel();
listener.cancel();
}
});
changes.on('error', reject);
listener.on('error', reject);

q.drain(() => {
changesConsumer.drain(() => {
if (npmSeqReached) {
log.info('🐌 We reached the npm current sequence');
resolve();
Expand All @@ -287,15 +267,14 @@ async function watch({ seq }) {
});

return new Promise((resolve, reject) => {
const changes = db.changes({
...defaultOptions,
const listener = npm.listenToChanges({
since: seq,
live: true,
batch_size: 1, // eslint-disable-line camelcase
return_docs: false, // eslint-disable-line camelcase
});

const q = queue(async change => {
const changesConsumer = queue(async change => {
datadog.increment('packages');

try {
Expand Down Expand Up @@ -325,18 +304,18 @@ async function watch({ seq }) {
}
}, 1);

changes.on('change', async change => {
listener.on('change', async change => {
if (change.deleted === true) {
await mainIndex.deleteObject(change.id);
log.info(`🛰 Deleted ${change.id}`);
}
q.push(change, err => {
changesConsumer.push(change, err => {
if (err) {
reject(err);
}
});
});
changes.on('error', reject);
listener.on('error', reject);
});
}

Expand Down
52 changes: 32 additions & 20 deletions src/__tests__/npm.test.js → src/npm/__tests__/index.test.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { info, getDownloads, getDependents } from '../npm';
import * as api from '../index.js';

describe('info()', () => {
describe('getInfo()', () => {
let registryInfo;
beforeAll(async () => {
registryInfo = await info();
registryInfo = await api.getInfo();
});

it('contains the correct keys', () => {
test('contains the correct keys', () => {
expect(registryInfo).toEqual(
expect.objectContaining({
nbDocs: expect.any(Number),
Expand All @@ -19,7 +19,7 @@ describe('info()', () => {
describe('getDependents()', () => {
let dependents;
beforeAll(async () => {
dependents = await getDependents([
dependents = await api.getDependents([
{ name: 'jest' },
{ name: '@angular/core' },
{ name: 'holmes.js' },
Expand Down Expand Up @@ -47,30 +47,42 @@ describe('getDependents()', () => {
expect(angular).toBe(0);
expect(holmes).toBe(0);
});
});

it.skip('has the right approximate value', () => {
const [jest, angular, holmes] = dependents.map(pkg =>
pkg.dependents.toString()
);

// eslint-disable-next-line no-console
console.log('dependents', { jest, angular, holmes });

// real should be 2100
expect(jest).toHaveLength(4);
describe('getDownload()', () => {
it('should download one package and return correct response', async () => {
const dl = await api.getDownload('jest');
expect(dl.body).toHaveProperty('jest');
expect(dl.body.jest).toEqual({
downloads: expect.any(Number),
start: expect.any(String),
end: expect.any(String),
package: 'jest',
});
});

// real should be 5200
expect(angular).toHaveLength(4);
it('should download one scoped package and return correct response', async () => {
const dl = await api.getDownload('@angular/core');
expect(dl.body).toHaveProperty('@angular/core');
expect(dl.body['@angular/core']).toEqual({
downloads: expect.any(Number),
start: expect.any(String),
end: expect.any(String),
package: '@angular/core',
});
});

// real should be 0
expect(holmes).toHaveLength(1);
it('should download 2 packages and return correct response', async () => {
const dl = await api.getDownload('jest,holmes.js');
bodinsamuel marked this conversation as resolved.
Show resolved Hide resolved
expect(dl.body).toHaveProperty('jest');
expect(dl.body).toHaveProperty(['holmes.js']);
});
});

describe('getDownloads()', () => {
let downloads;
beforeAll(async () => {
downloads = await getDownloads([
downloads = await api.getDownloads([
{ name: 'jest' },
{ name: '@angular/core' },
{ name: 'holmes.js' },
Expand Down
Loading