Skip to content

Commit e0bdae5

Browse files
committed
own the state
Signed-off-by: Tobias Gurtzick <[email protected]>
1 parent c523073 commit e0bdae5

File tree

1 file changed

+42
-4
lines changed

1 file changed

+42
-4
lines changed

lib/state.js

Lines changed: 42 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,68 @@
11
const MSTATE = '__dbmigrate_state__';
22
const SSTATE = '__dbmigrate_schema__';
3+
const RUNON =
4+
'run_on';
5+
36
const log = require('db-migrate-shared').log;
47
const fs = require('fs').promises;
58
const path = require('path');
9+
const crypto = require('crypto');
10+
11+
const ID = crypto.randomBytes(32).toString('base64');
12+
let owner = false;
613

714
module.exports = {
15+
/**
16+
* Lock state will add the basic state controller an ID
17+
* and a process controlled date.
18+
* It is important that all systems are in sync. We will use the
19+
* database clock instead if possible.
20+
*/
821
lockState: async function (driver, state, internals) {
922
if (!state) {
23+
owner = true;
1024
return driver._insertKV(
1125
internals.migrationState,
1226
MSTATE,
1327
JSON.stringify({
1428
s: {
1529
step: 0,
1630
fin: 0,
31+
ID,
1732
date: new Date()
1833
}
1934
})
2035
);
2136
} else {
37+
let runOn = state.run_on;
2238
state = state.value;
2339
state = JSON.parse(state);
24-
state.s.date = new Date();
25-
return driver._updateKV(
40+
41+
if (!state.s.ID || state.s.ID !== ID) {
42+
owner = true;
43+
state.s.ID = ID;
44+
}
45+
46+
const d = new Date();
47+
48+
state.s.date = d;
49+
await driver._updateKVC(
2650
internals.migrationState,
2751
MSTATE,
28-
29-
JSON.stringify(state)
52+
JSON.stringify(state),
53+
RUNON,
54+
runOn
3055
);
56+
57+
state = await driver._getKV(internals.migrationState, MSTATE);
58+
59+
runOn = state.run_on;
60+
state = state.value;
61+
state = JSON.parse(state);
62+
63+
if (state.s.ID !== ID) {
64+
owner = false;
65+
}
3166
}
3267
},
3368

@@ -165,6 +200,9 @@ module.exports = {
165200
state.s.date = new Date();
166201
state.s.fin = 1;
167202

203+
// unlock from current process
204+
state.s.ID = 0;
205+
168206
return driver._updateKV(
169207
internals.migrationState,
170208
MSTATE,

0 commit comments

Comments
 (0)