@kapeta/local-cluster-service 0.5.10 → 0.5.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,17 @@
1
+ ## [0.5.12](https://github.com/kapetacom/local-cluster-service/compare/v0.5.11...v0.5.12) (2023-06-21)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * await asset deletion and only cache successful web requests ([663a4a7](https://github.com/kapetacom/local-cluster-service/commit/663a4a7987385f9a0550d6149a23b7a9de08b226))
7
+
8
+ ## [0.5.11](https://github.com/kapetacom/local-cluster-service/compare/v0.5.10...v0.5.11) (2023-06-20)
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * Improve path template parser. ([#36](https://github.com/kapetacom/local-cluster-service/issues/36)) ([b655da1](https://github.com/kapetacom/local-cluster-service/commit/b655da1e97740ff2b4fe0f2bcd7f75b04003753e))
14
+
1
15
  ## [0.5.10](https://github.com/kapetacom/local-cluster-service/compare/v0.5.9...v0.5.10) (2023-06-19)
2
16
 
3
17
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kapeta/local-cluster-service",
3
- "version": "0.5.10",
3
+ "version": "0.5.12",
4
4
  "description": "Manages configuration, ports and service discovery for locally running Kapeta systems",
5
5
  "main": "index.js",
6
6
  "repository": {
@@ -2,9 +2,8 @@ const Router = require('express-promise-router').default;
2
2
  const YAML = require('yaml');
3
3
  const assetManager = require('../assetManager');
4
4
 
5
-
6
5
  function parseBody(req) {
7
- switch(req.headers['content-type']) {
6
+ switch (req.headers['content-type']) {
8
7
  case 'application/json':
9
8
  case 'application/x-json':
10
9
  case 'text/json':
@@ -36,16 +35,15 @@ router.get('/', (req, res) => {
36
35
  */
37
36
  router.get('/read', async (req, res) => {
38
37
  if (!req.query.ref) {
39
- res.status(400).send({error:'Query parameter "ref" is missing'});
38
+ res.status(400).send({ error: 'Query parameter "ref" is missing' });
40
39
  return;
41
40
  }
42
41
 
43
42
  try {
44
43
  res.send(await assetManager.getAsset(req.query.ref, true));
45
- } catch(err) {
46
- res.status(400).send({error: err.message});
44
+ } catch (err) {
45
+ res.status(400).send({ error: err.message });
47
46
  }
48
-
49
47
  });
50
48
 
51
49
  /**
@@ -53,7 +51,7 @@ router.get('/read', async (req, res) => {
53
51
  */
54
52
  router.post('/create', async (req, res) => {
55
53
  if (!req.query.path) {
56
- res.status(400).send({error:'Query parameter "path" is missing'});
54
+ res.status(400).send({ error: 'Query parameter "path" is missing' });
57
55
  return;
58
56
  }
59
57
 
@@ -63,11 +61,10 @@ router.post('/create', async (req, res) => {
63
61
  const assets = await assetManager.createAsset(req.query.path, content);
64
62
 
65
63
  res.status(200).send(assets);
66
- } catch(err) {
64
+ } catch (err) {
67
65
  console.log('Failed while creating asset', req.query.path, err.message);
68
- res.status(400).send({error: err.message});
66
+ res.status(400).send({ error: err.message });
69
67
  }
70
-
71
68
  });
72
69
 
73
70
  /**
@@ -75,7 +72,7 @@ router.post('/create', async (req, res) => {
75
72
  */
76
73
  router.put('/update', async (req, res) => {
77
74
  if (!req.query.ref) {
78
- res.status(400).send({error:'Query parameter "ref" is missing'});
75
+ res.status(400).send({ error: 'Query parameter "ref" is missing' });
79
76
  return;
80
77
  }
81
78
 
@@ -85,39 +82,36 @@ router.put('/update', async (req, res) => {
85
82
  await assetManager.updateAsset(req.query.ref, content);
86
83
 
87
84
  res.sendStatus(204);
88
- } catch(err) {
85
+ } catch (err) {
89
86
  console.log('Failed while updating asset', req.query.ref, err.message);
90
- res.status(400).send({error: err.message});
87
+ res.status(400).send({ error: err.message });
91
88
  }
92
-
93
89
  });
94
90
 
95
-
96
91
  /**
97
92
  * Unregisters an asset (doesn't delete the asset)
98
93
  */
99
- router.delete('/', (req, res) => {
94
+ router.delete('/', async (req, res) => {
100
95
  if (!req.query.ref) {
101
- res.status(400).send({error:'Query parameter "ref" is missing'});
96
+ res.status(400).send({ error: 'Query parameter "ref" is missing' });
102
97
  return;
103
98
  }
104
99
 
105
100
  try {
106
- assetManager.unregisterAsset(req.query.ref);
101
+ await assetManager.unregisterAsset(req.query.ref);
107
102
 
108
103
  res.status(204).send();
109
- } catch(err) {
110
- res.status(400).send({error: err.message});
104
+ } catch (err) {
105
+ res.status(400).send({ error: err.message });
111
106
  }
112
107
  });
113
108
 
114
-
115
109
  /**
116
110
  * Registers an existing file as an asset
117
111
  */
118
112
  router.put('/import', async (req, res) => {
119
113
  if (!req.query.ref) {
120
- res.status(400).send({error:'Query parameter "ref" is missing'});
114
+ res.status(400).send({ error: 'Query parameter "ref" is missing' });
121
115
  return;
122
116
  }
123
117
 
@@ -125,9 +119,9 @@ router.put('/import', async (req, res) => {
125
119
  const assets = await assetManager.importFile(req.query.ref);
126
120
 
127
121
  res.status(200).send(assets);
128
- } catch(err) {
129
- res.status(400).send({error: err.message});
122
+ } catch (err) {
123
+ res.status(400).send({ error: err.message });
130
124
  }
131
125
  });
132
126
 
133
- module.exports = router;
127
+ module.exports = router;
@@ -1,40 +1,52 @@
1
1
  const FS = require('fs');
2
2
  const Path = require('path');
3
3
  const FSExtra = require('fs-extra');
4
- const repositoryManager = require('./repositoryManager')
4
+ const repositoryManager = require('./repositoryManager');
5
5
  const ClusterConfiguration = require('@kapeta/local-cluster-config').default;
6
6
 
7
7
  class ProviderManager {
8
-
9
8
  constructor() {
10
9
  this._webAssetCache = {};
11
10
  }
12
11
 
13
12
  getWebProviders() {
14
- return ClusterConfiguration
15
- .getProviderDefinitions()
16
- .filter((providerDefinition) => providerDefinition.hasWeb)
13
+ return ClusterConfiguration.getProviderDefinitions().filter(
14
+ (providerDefinition) => providerDefinition.hasWeb
15
+ );
17
16
  }
18
17
 
19
18
  async getAsset(handle, name, version, sourceMap = false) {
20
19
  const fullName = `${handle}/${name}`;
21
- const id = `${handle}/${name}/${version}/web.js${sourceMap ? '.map' : ''}`;
22
-
23
- if (this._webAssetCache[id] &&
24
- await FSExtra.pathExists(this._webAssetCache[id])) {
25
- return FSExtra.readFile(this._webAssetCache[id]);
20
+ const id = `${handle}/${name}/${version}/web.js${
21
+ sourceMap ? '.map' : ''
22
+ }`;
23
+
24
+ if (
25
+ this._webAssetCache[id] &&
26
+ (await FSExtra.pathExists(this._webAssetCache[id]))
27
+ ) {
28
+ return FSExtra.readFile(this._webAssetCache[id], 'utf8');
26
29
  }
27
30
 
28
31
  await repositoryManager.ensureAsset(handle, name, version);
29
32
 
30
- const installedProvider = this.getWebProviders().find((providerDefinition) => {
31
- return providerDefinition.definition.metadata.name === fullName &&
32
- providerDefinition.version === version;
33
- })
33
+ const installedProvider = this.getWebProviders().find(
34
+ (providerDefinition) => {
35
+ return (
36
+ providerDefinition.definition.metadata.name === fullName &&
37
+ providerDefinition.version === version
38
+ );
39
+ }
40
+ );
34
41
 
35
42
  if (installedProvider) {
36
43
  //Check locally installed providers
37
- const path = Path.join(installedProvider.path, 'web', handle, `${name}.js${sourceMap ? '.map' : ''}`);
44
+ const path = Path.join(
45
+ installedProvider.path,
46
+ 'web',
47
+ handle,
48
+ `${name}.js${sourceMap ? '.map' : ''}`
49
+ );
38
50
  if (await FSExtra.pathExists(path)) {
39
51
  this._webAssetCache[id] = path;
40
52
 
@@ -50,10 +62,15 @@ const providerDefinitions = ClusterConfiguration.getProviderDefinitions();
50
62
 
51
63
  if (providerDefinitions.length > 0) {
52
64
  console.log('## Loaded the following providers ##');
53
- providerDefinitions.forEach(providerDefinition => {
54
- console.log(' - %s[%s:%s]', providerDefinition.definition.kind, providerDefinition.definition.metadata.name, providerDefinition.version);
65
+ providerDefinitions.forEach((providerDefinition) => {
66
+ console.log(
67
+ ' - %s[%s:%s]',
68
+ providerDefinition.definition.kind,
69
+ providerDefinition.definition.metadata.name,
70
+ providerDefinition.version
71
+ );
55
72
  console.log(' from %s', providerDefinition.path);
56
- })
73
+ });
57
74
  } else {
58
75
  console.log('## No providers found ##');
59
76
  }
@@ -12,37 +12,32 @@ router.get('/', async (req, res) => {
12
12
  });
13
13
 
14
14
  router.get('/asset/:handle/:name/:version/web.js', async (req, res) => {
15
-
16
- const {handle, name, version} = req.params;
15
+ const { handle, name, version } = req.params;
17
16
  let result = await providerManager.getAsset(handle, name, version);
18
17
 
19
- if (version !== 'local') {
20
- res.setHeader('Cache-Control', 'max-age=31536000, immutable');
21
- }
22
-
23
18
  if (!result) {
24
19
  res.status(404).send('');
25
20
  } else {
26
- res.send(result.toString()
27
- .replace(`${name}.js.map`, 'web.js.map')
28
- );
21
+ if (version !== 'local') {
22
+ res.setHeader('Cache-Control', 'max-age=31536000, immutable');
23
+ }
24
+ res.send(result.toString().replace(`${name}.js.map`, 'web.js.map'));
29
25
  }
30
26
  });
31
27
 
32
28
  router.get('/asset/:handle/:name/:version/web.js.map', async (req, res) => {
33
-
34
- const {handle, name, version} = req.params;
29
+ const { handle, name, version } = req.params;
35
30
  const result = await providerManager.getAsset(handle, name, version, true);
36
- if (version !== 'local') {
37
- res.setHeader('Cache-Control', 'max-age=31536000, immutable');
38
- }
39
31
 
40
32
  if (!result) {
41
33
  res.status(404).send('');
42
34
  } else {
35
+ // Only cache successful requests
36
+ if (version !== 'local') {
37
+ res.setHeader('Cache-Control', 'max-age=31536000, immutable');
38
+ }
43
39
  res.send(result);
44
40
  }
45
41
  });
46
42
 
47
-
48
- module.exports = router;
43
+ module.exports = router;
@@ -1,23 +1,24 @@
1
- const ClusterConfiguration = require("@kapeta/local-cluster-config").default;
2
- const FS = require("node:fs");
3
- const FSExtra = require("fs-extra");
4
- const Path = require("node:path");
5
- const socketManager = require("./socketManager");
6
- const {Actions, RegistryService, Config} = require("@kapeta/nodejs-registry-utils");
7
- const progressListener = require("./progressListener");
8
- const os = require("os");
9
- const {parseKapetaUri} = require("@kapeta/nodejs-utils");
1
+ const ClusterConfiguration = require('@kapeta/local-cluster-config').default;
2
+ const FS = require('node:fs');
3
+ const FSExtra = require('fs-extra');
4
+ const Path = require('node:path');
5
+ const socketManager = require('./socketManager');
6
+ const {
7
+ Actions,
8
+ RegistryService,
9
+ Config,
10
+ } = require('@kapeta/nodejs-registry-utils');
11
+ const progressListener = require('./progressListener');
12
+ const os = require('os');
13
+ const { parseKapetaUri } = require('@kapeta/nodejs-utils');
10
14
  const INSTALL_ATTEMPTED = {};
11
15
 
12
16
  class RepositoryManager {
13
-
14
17
  constructor() {
15
18
  this.watcher = null;
16
19
  this.changeEventsEnabled = true;
17
20
  this.listenForChanges();
18
- this._registryService = new RegistryService(
19
- Config.data.registry.url
20
- );
21
+ this._registryService = new RegistryService(Config.data.registry.url);
21
22
  this._cache = {};
22
23
  this._installQueue = [];
23
24
  }
@@ -32,16 +33,20 @@ class RepositoryManager {
32
33
  FSExtra.mkdirpSync(baseDir);
33
34
  }
34
35
 
35
- let allDefinitions = ClusterConfiguration
36
- .getDefinitions();
36
+ let allDefinitions = ClusterConfiguration.getDefinitions();
37
37
 
38
- console.log('Watching local repository for provider changes: %s', baseDir);
38
+ console.log(
39
+ 'Watching local repository for provider changes: %s',
40
+ baseDir
41
+ );
39
42
  try {
40
43
  this.watcher = FS.watch(baseDir, { recursive: true });
41
44
  } catch (e) {
42
45
  // Fallback to run without watch mode due to potential platform issues.
43
46
  // https://nodejs.org/docs/latest/api/fs.html#caveats
44
- console.log('Unable to watch for changes. Changes to assets will not update automatically.');
47
+ console.log(
48
+ 'Unable to watch for changes. Changes to assets will not update automatically.'
49
+ );
45
50
  return;
46
51
  }
47
52
  this.watcher.on('change', (eventType, filename) => {
@@ -54,11 +59,21 @@ class RepositoryManager {
54
59
  return;
55
60
  }
56
61
 
57
- const ymlPath = Path.join(baseDir, handle, name, version, 'kapeta.yml');
62
+ const ymlPath = Path.join(
63
+ baseDir,
64
+ handle,
65
+ name,
66
+ version,
67
+ 'kapeta.yml'
68
+ );
58
69
  const newDefinitions = ClusterConfiguration.getDefinitions();
59
70
 
60
- const newDefinition = newDefinitions.find(d => d.ymlPath === ymlPath);
61
- let currentDefinition = allDefinitions.find(d => d.ymlPath === ymlPath);
71
+ const newDefinition = newDefinitions.find(
72
+ (d) => d.ymlPath === ymlPath
73
+ );
74
+ let currentDefinition = allDefinitions.find(
75
+ (d) => d.ymlPath === ymlPath
76
+ );
62
77
  const ymlExists = FS.existsSync(ymlPath);
63
78
  let type;
64
79
  if (ymlExists) {
@@ -85,9 +100,13 @@ class RepositoryManager {
85
100
  }
86
101
  }
87
102
 
88
- const payload = {type, definition: currentDefinition?.definition, asset: {handle, name, version} };
103
+ const payload = {
104
+ type,
105
+ definition: currentDefinition?.definition,
106
+ asset: { handle, name, version },
107
+ };
89
108
 
90
- allDefinitions = newDefinitions
109
+ allDefinitions = newDefinitions;
91
110
  socketManager.emit(`assets`, 'changed', payload);
92
111
  });
93
112
  }
@@ -108,21 +127,42 @@ class RepositoryManager {
108
127
  const out = new Promise((resolve, reject) => {
109
128
  this._installQueue.push(async () => {
110
129
  try {
111
- const normalizedRefs = refs.map(ref => parseKapetaUri(ref).id)
112
- const filteredRefs = normalizedRefs.filter(ref => !INSTALL_ATTEMPTED[ref]);
130
+ const normalizedRefs = refs.map(
131
+ (ref) => parseKapetaUri(ref).id
132
+ );
133
+ const filteredRefs = normalizedRefs.filter(
134
+ (ref) => !INSTALL_ATTEMPTED[ref]
135
+ );
136
+ console.log(filteredRefs);
113
137
  if (filteredRefs.length > 0) {
114
- filteredRefs.forEach(ref => INSTALL_ATTEMPTED[ref] = true);
138
+ filteredRefs.forEach(
139
+ (ref) => (INSTALL_ATTEMPTED[ref] = true)
140
+ );
115
141
  //Auto-install missing asset
116
142
  try {
117
143
  //We change to a temp dir to avoid issues with the current working directory
118
144
  process.chdir(os.tmpdir());
119
145
  //Disable change events while installing
120
146
  this.setChangeEventsEnabled(false);
121
- socketManager.emit(`install`, 'install:action', {type: 'start', refs});
122
- await Actions.install(progressListener, normalizedRefs, {});
123
- socketManager.emit(`install`, 'install:action', {type: 'done', refs});
147
+ socketManager.emit(`install`, 'install:action', {
148
+ type: 'start',
149
+ refs,
150
+ });
151
+ await Actions.install(
152
+ progressListener,
153
+ normalizedRefs,
154
+ {}
155
+ );
156
+ socketManager.emit(`install`, 'install:action', {
157
+ type: 'done',
158
+ refs,
159
+ });
124
160
  } catch (e) {
125
- socketManager.emit(`install`, 'install:action', {type: 'failed', refs, error: e.message});
161
+ socketManager.emit(`install`, 'install:action', {
162
+ type: 'failed',
163
+ refs,
164
+ error: e.message,
165
+ });
126
166
  } finally {
127
167
  this.setChangeEventsEnabled(true);
128
168
  }
@@ -131,12 +171,12 @@ class RepositoryManager {
131
171
  } catch (e) {
132
172
  reject(e);
133
173
  } finally {
134
- this._processNext().catch(e => console.error(e));
174
+ this._processNext().catch((e) => console.error(e));
135
175
  }
136
- })
176
+ });
137
177
  });
138
178
 
139
- this._processNext().catch(e => console.error(e));
179
+ this._processNext().catch((e) => console.error(e));
140
180
 
141
181
  return out;
142
182
  }
@@ -167,10 +207,10 @@ class RepositoryManager {
167
207
  }
168
208
 
169
209
  const definitions = ClusterConfiguration.getDefinitions();
170
- const installedAsset = definitions.find(d =>
171
- d.definition.metadata.name === fullName &&
172
- d.version === version);
173
-
210
+ const installedAsset = definitions.find(
211
+ (d) =>
212
+ d.definition.metadata.name === fullName && d.version === version
213
+ );
174
214
 
175
215
  if (installedAsset && this._cache[ref] === true) {
176
216
  return;
@@ -182,7 +222,10 @@ class RepositoryManager {
182
222
 
183
223
  let assetVersion;
184
224
  try {
185
- assetVersion = await this._registryService.getVersion(fullName, version);
225
+ assetVersion = await this._registryService.getVersion(
226
+ fullName,
227
+ version
228
+ );
186
229
  if (!assetVersion) {
187
230
  this._cache[ref] = false;
188
231
  return;
@@ -205,9 +248,7 @@ class RepositoryManager {
205
248
  console.log(`Auto-installing dependencies: ${refs.join(', ')}`);
206
249
  await this._install(refs);
207
250
  }
208
-
209
-
210
251
  }
211
252
  }
212
253
 
213
- module.exports = new RepositoryManager();
254
+ module.exports = new RepositoryManager();
@@ -2,6 +2,17 @@
2
2
  const TYPE_VARIABLE = 'variable';
3
3
  const TYPE_PATH = 'path';
4
4
 
5
+ /**
6
+ * A path template is a string that can be used to match a path and extract variables from it.
7
+ *
8
+ * E.g. /foo/{bar}/baz
9
+ *
10
+ * Would match /foo/123/baz and extract bar=123
11
+ *
12
+ * You can also specify a regex for the variable:
13
+ * /foo/{bar:[0-9]+}/baz
14
+ *
15
+ */
5
16
  class PathTemplate {
6
17
  constructor(pathTemplate) {
7
18
  if (!pathTemplate.startsWith('/')) {
@@ -9,33 +20,41 @@ class PathTemplate {
9
20
  }
10
21
  this._path = pathTemplate;
11
22
 
12
- this._parts = pathTemplate.split(/{/g).map((part) => {
13
- if (part.endsWith('}')) {
14
- let regex,
15
- value = part.substr(0, part.length - 1);
16
-
17
- [value, regex] = value.split(/:/, 2);
23
+ const variableRegex = /{([^}]+)}/g;
24
+ let match, offset = 0;
25
+ this._parts = [];
26
+ while((match = variableRegex.exec(pathTemplate)) !== null) {
27
+ if (match.index > offset) {
28
+ this._parts.push({
29
+ type: TYPE_PATH,
30
+ value: pathTemplate.substring(offset, match.index)
31
+ });
32
+ }
18
33
 
19
- if (regex) {
20
- regex = new RegExp('^' + regex);
21
- } else {
22
- regex = /^[^\/]+/
23
- }
34
+ let regex;
35
+ let value = match[1];
36
+ [value, regex] = value.split(/:/, 2);
24
37
 
25
- return {
26
- type: TYPE_VARIABLE,
27
- value,
28
- regex
29
- };
38
+ if (regex) {
39
+ regex = new RegExp('^' + regex);
40
+ } else {
41
+ regex = /^[^\/]+/
30
42
  }
31
43
 
32
- return {
33
- type: TYPE_PATH,
34
- value: part
35
- };
36
- });
37
-
44
+ this._parts.push({
45
+ type: TYPE_VARIABLE,
46
+ value,
47
+ regex
48
+ });
49
+ offset = match.index + match[0].length;
50
+ }
38
51
 
52
+ if (offset < pathTemplate.length) {
53
+ this._parts.push({
54
+ type: TYPE_PATH,
55
+ value: pathTemplate.substring(offset)
56
+ });
57
+ }
39
58
  }
40
59
 
41
60
  get path() {
@@ -61,7 +80,7 @@ class PathTemplate {
61
80
  return null;
62
81
  }
63
82
 
64
- path = path.substr(part.value.length);
83
+ path = path.substring(part.value.length);
65
84
  break;
66
85
  case TYPE_VARIABLE:
67
86
  if (!part.regex.test(path)) {