Skip to content

Commit c6c2905

Browse files
author
Zebedeusz
authored
Merge pull request #270 from pryv/feature/user-agent-pryv.io-with-api-version
Feature/user agent pryv.io with api version
2 parents 895667b + 273ca4d commit c6c2905

File tree

13 files changed

+91
-100
lines changed

13 files changed

+91
-100
lines changed

.vscode/snipsnap.code-snippets

Lines changed: 1 addition & 0 deletions
Large diffs are not rendered by default.

components/api-server/src/expressApp.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ class ExpressAppLifecycle {
127127
//
128128
async function expressAppInit(dependencies: any, isDNSLess: boolean) {
129129
const pv = new ProjectVersion();
130-
const version = await pv.version();
130+
const version = pv.version();
131131

132132
dependencies.register('airbrakeNotifier', {airbrakeNotifier: createAirbrakeNotifierIfNeeded()});
133133

components/api-server/src/methods/events.js

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,9 @@ var utils = require('components/utils'),
1818
SetFileReadTokenStream = require('./streams/SetFileReadTokenStream');
1919

2020
const assert = require('assert');
21-
21+
22+
const { ProjectVersion } = require('components/middleware/src/project_version');
23+
2224
const {TypeRepository, isSeriesType} = require('components/business').types;
2325

2426

@@ -44,8 +46,13 @@ module.exports = function (
4446
auditSettings, updatesSettings, openSourceSettings,
4547
) {
4648

49+
50+
// Initialise the project version as soon as we can.
51+
const pv = new ProjectVersion();
52+
let version = pv.version();
53+
4754
// Update types and log error
48-
typeRepo.tryUpdate(eventTypesUrl)
55+
typeRepo.tryUpdate(eventTypesUrl, version)
4956
.catch((err) => logging.getLogger('typeRepo').warn(err));
5057

5158
const logger = logging.getLogger('methods/events');

components/api-server/src/methods/helpers/setCommonMeta.js

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,7 @@ let config: ConfigAccess = null;
3535

3636
// Initialise the project version as soon as we can.
3737
const pv = new ProjectVersion();
38-
(async () => {
39-
version = await pv.version();
40-
})();
41-
38+
version = pv.version();
4239

4340
/**
4441
*

components/business/src/types.js

Lines changed: 30 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
// TypeRepository is the repository for all Pryv event types. It allows access
1010
// to coercion and validation.
1111

12-
import type {EventType, Content} from './types/interfaces';
12+
import type { EventType, Content } from './types/interfaces';
1313

1414
const lodash = require('lodash');
1515
const superagent = require('superagent');
@@ -35,26 +35,25 @@ function isSeriesType(name: string): boolean {
3535
// A validator that can check values against a types JSON Schema.
3636
//
3737
class TypeValidator {
38-
38+
3939
// Validates the given event type against its schema.
4040
//
4141
validate(type: EventType, content: Content): Promise<Content> {
4242
return type.callValidator(this, content);
4343
}
44-
44+
4545
validateWithSchema(
46-
content: Content,
46+
content: Content,
4747
schema: any
48-
): Promise<Content>
49-
{
48+
): Promise<Content> {
5049
return bluebird.try(() => {
51-
const validator = new ZSchemaValidator();
52-
50+
const validator = new ZSchemaValidator();
51+
5352
return bluebird
5453
.fromCallback(
5554
(cb) => validator.validate(content, schema, cb))
5655
.then(() => content);
57-
});
56+
});
5857
}
5958
}
6059

@@ -92,10 +91,10 @@ class TypeRepository {
9291
//
9392
isKnown(name: string): boolean {
9493
if (isSeriesType(name)) {
95-
const leafTypeName = name.slice(SERIES_PREFIX.length);
94+
const leafTypeName = name.slice(SERIES_PREFIX.length);
9695
return this.isKnown(leafTypeName);
9796
}
98-
97+
9998
return defaultTypes.types.hasOwnProperty(name);
10099
}
101100

@@ -104,18 +103,18 @@ class TypeRepository {
104103
// `event-types.default.json`.
105104
//
106105
lookupLeafType(name: string): EventType {
107-
if (! this.isKnown(name)) throw new errors.TypeDoesNotExistError(
106+
if (!this.isKnown(name)) throw new errors.TypeDoesNotExistError(
108107
`Type '${name}' does not exist in this Pryv instance.`);
109108

110109
const typeSchema = defaultTypes.types[name];
111110

112111
if (typeSchema.type === 'object') {
113112
return new ComplexType(name, typeSchema);
114113
}
115-
114+
116115
return new BasicType(name, typeSchema);
117116
}
118-
117+
119118
// Lookup a Pryv Event Type by name. To check if a type exists, use
120119
// `#isKnown`. Pryv types are either leaf types ('mass/kg', 'position/wgs84')
121120
// or series types ('series:LEAFTYPE').
@@ -124,48 +123,51 @@ class TypeRepository {
124123
//
125124
lookup(name: string) {
126125
if (isSeriesType(name)) {
127-
const leafTypeName = name.slice(SERIES_PREFIX.length);
126+
const leafTypeName = name.slice(SERIES_PREFIX.length);
128127
const leafType = this.lookupLeafType(leafTypeName);
129-
128+
130129
return new InfluxRowType(leafType);
131130
}
132-
131+
133132
// assert: Not a series type, must be a leaf type.
134133
return this.lookupLeafType(name);
135134
}
136135

137136
// Produces a validator instance.
138137
//
139138
validator(): TypeValidator {
140-
return new TypeValidator();
139+
return new TypeValidator();
141140
}
142141

143142
// Tries to update the stored type definitions with a file found on the
144143
// internet.
145144
//
146-
tryUpdate(sourceURL: string): Promise<void> {
145+
tryUpdate(sourceURL: string, apiVersion: string): Promise<void> {
147146
function unavailableError(err) {
148147
throw new Error(
149148
'Could not update event types from ' + sourceURL +
150149
'\nError: ' + err.message);
151150
}
152151
function invalidError(err) {
153152
throw new Error(
154-
'Invalid event types schema returned from ' + sourceURL +
153+
'Invalid event types schema returned from ' + sourceURL +
155154
'\nErrors: ' + err.errors);
156155
}
157-
156+
157+
const USER_AGENT_PREFIX: string = 'Pryv.io/';
158+
158159
return superagent
159160
.get(sourceURL)
161+
.set('User-Agent', USER_AGENT_PREFIX + apiVersion)
160162
.catch(unavailableError)
161163
.then((res) => {
162-
const validator = new ZSchemaValidator();
163-
const schema = res.body;
164-
164+
const validator = new ZSchemaValidator();
165+
const schema = res.body;
166+
165167
return bluebird.try(() => {
166-
if (!validator.validateSchema(schema))
168+
if (!validator.validateSchema(schema))
167169
return invalidError(validator.lastReport);
168-
170+
169171
// Overwrite defaultTypes with the merged list of type schemata.
170172
defaultTypes = lodash.merge(defaultTypes, schema);
171173
});
@@ -174,10 +176,10 @@ class TypeRepository {
174176
}
175177

176178
module.exports = {
177-
TypeRepository: TypeRepository,
179+
TypeRepository: TypeRepository,
178180
InfluxRowType: InfluxRowType,
179181
isSeriesType: isSeriesType,
180-
errors: errors,
182+
errors: errors,
181183
};
182184

183185
export type { InfluxRowType };

components/business/src/webhooks/Webhook.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,7 @@ class Webhook implements MessageSink {
248248
_.merge(this, fieldsToUpdate);
249249
await makeUpdate(fields, this);
250250
}
251-
251+
252252
async delete(): Promise<void> {
253253
if (this.repository == null) {
254254
throw new Error('repository not set for Webhook object.');

components/business/test/acceptance/webhooks/Webhook.test.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,9 @@ describe('Webhook', () => {
5050
});
5151

5252
let apiVersion;
53-
before(async () => {
53+
before(() => {
5454
const pv = new ProjectVersion();
55-
apiVersion = await pv.version();
55+
apiVersion = pv.version();
5656
});
5757

5858
after(() => {

components/hfs-server/src/server.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -134,14 +134,14 @@ class Server {
134134
*
135135
* @return express application.
136136
*/
137-
async setupExpress(): Promise<express$Application> {
137+
setupExpress(): Promise<express$Application> {
138138
const logger = this.logger;
139139
const settings = this.settings;
140140
const logSettings = settings.get('logs').obj();
141141
const traceEnabled = settings.get('trace.enable').bool();
142142

143143
const pv = new ProjectVersion();
144-
const version = await pv.version();
144+
const version = pv.version();
145145

146146
var app = express();
147147

components/middleware/src/project_version.js

Lines changed: 7 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -14,15 +14,14 @@ const bluebird = require('bluebird');
1414
const child_process = require('child_process');
1515

1616
const API_VERSION_FILENAME = '.api-version';
17+
const DEFAULT_VERSION = 'unset';
1718

1819
// The method '#version' returns a version string for this project; it
19-
// determines it using one of two methods:
20+
// determines it using the following:
2021
//
21-
// a) If the project contains a file called '.api-version' at its root,
22-
// the contents of the file are returned as version string. Take care
23-
// to strip newlines from the file.
24-
// b) Otherwise, we try to run 'git describe' and use the output from this
25-
// command.
22+
// If the project contains a file called '.api-version' at its root,
23+
// the contents of the file are returned as version string.
24+
// Take care to strip newlines from the file.
2625
//
2726
// The way we find the project root is as follows: Look at the paths in
2827
// 'process.mainModule' - and try to find the first one which does exist. This
@@ -37,28 +36,11 @@ const API_VERSION_FILENAME = '.api-version';
3736
class ProjectVersion {
3837
// Returns the projects version number.
3938
//
40-
async version(): Promise<string> {
39+
version(): string {
4140
const version = this.readStaticVersion();
4241
if (version != null) return version;
4342

44-
// NOTE If we get here, we better be in a development environment. Otherwise
45-
// we will try to run git describe and fail, throwing an error in the
46-
// process.
47-
48-
return await this.gitVersion();
49-
}
50-
51-
async gitVersion(): Promise<string> {
52-
const version = await this.exec('git describe');
53-
54-
return version.slice(0, -1);
55-
}
56-
57-
async exec(cmd: string): Promise<string> {
58-
const exec = (cmd) => bluebird.fromCallback(
59-
cb => child_process.exec(cmd, cb));
60-
61-
return exec(cmd);
43+
return DEFAULT_VERSION;
6244
}
6345

6446
readStaticVersion(): ?string {
@@ -71,7 +53,6 @@ class ProjectVersion {
7153

7254
// If the version file does not exist, give up.
7355
if (! fs.existsSync(versionFilePath)) continue;
74-
7556
return fs.readFileSync(versionFilePath).toString();
7657
}
7758

components/middleware/test/unit/project_version.test.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
const path = require('path');
1111

1212
const chai = require('chai');
13-
const assert = chai.assert;
13+
const assert = chai.assert;
1414
const sinon = require('sinon');
1515

1616
const bluebird = require('bluebird');
@@ -22,14 +22,14 @@ const { ProjectVersion } = require('../../src/project_version');
2222
describe('ProjectVersion#version', () => {
2323
let pv;
2424
beforeEach(() => {
25-
pv = new ProjectVersion();
25+
pv = new ProjectVersion();
2626
});
27-
27+
2828
describe('when a ".api-version" file exists in the project', () => {
2929
const versionFilePath = path.join(__dirname, '../../../../../', '.api-version');
30-
30+
3131
it('[HV40] reads .api-version and returns that constant', async () => {
32-
assert.strictEqual(await pv.version(), '1.2.3');
32+
assert.strictEqual(pv.version(), '1.2.3');
3333
});
3434
});
3535
});

0 commit comments

Comments
 (0)