poad 2.51.0 → 2.53.0
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/package.json +1 -1
- package/project/cli.js +9 -0
- package/project/seed/index.js +18 -0
- package/project/seed/inspect.js +45 -0
- package/project/seed/load.js +50 -0
- package/project/seed/ls.js +27 -0
- package/project/seed/mode.js +14 -0
- package/project/seed/push.js +109 -0
- package/project/seed/rm.js +14 -0
- package/test/seed.test.js +168 -0
- package/utils/seed/apply.js +155 -0
- package/utils/seed/convert.js +687 -0
- package/utils/seed/inspect.js +233 -0
- package/utils/seed/pack.js +179 -0
- package/utils/seed/report.js +37 -0
- package/utils/seed/run.js +214 -0
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
// Seed inspector : ce que contient un fichier de données, colonne par colonne,
|
|
2
|
+
// avant tout envoi. L'essentiel est la VOLUMÉTRIE, quelle que soit la nature de
|
|
3
|
+
// la donnée (géométrie, long texte, binaire d'une image ou d'une vidéo, JSON) :
|
|
4
|
+
// part du volume de chaque colonne, taille moyenne et maximale d'une valeur,
|
|
5
|
+
// colonnes lourdes signalées. Le type deviné ne sert qu'à estimer la place que
|
|
6
|
+
// la table prendra dans la base (PostgreSQL), index compris.
|
|
7
|
+
// Tout est calculé sur le poste, en un passage, sans rien garder en mémoire
|
|
8
|
+
// d'autre que des compteurs.
|
|
9
|
+
'use strict';
|
|
10
|
+
|
|
11
|
+
const GEOM_TYPES = { 1: 'Point', 2: 'LineString', 3: 'Polygon', 4: 'MultiPoint', 5: 'MultiLineString', 6: 'MultiPolygon', 7: 'GeometryCollection' };
|
|
12
|
+
|
|
13
|
+
/** En-tête EWKB (hexadécimal) : { type, srid } ou null */
|
|
14
|
+
function ewkbHeader(hex) {
|
|
15
|
+
if (hex.length < 10 || hex.length % 2 || !/^0[01]/.test(hex)) return null;
|
|
16
|
+
const little = hex[1] === '1';
|
|
17
|
+
const u32 = (at) => {
|
|
18
|
+
const b = hex.slice(at, at + 8);
|
|
19
|
+
if (b.length < 8 || !/^[0-9A-Fa-f]{8}$/.test(b)) return null;
|
|
20
|
+
const bytes = b.match(/../g).map((x) => parseInt(x, 16));
|
|
21
|
+
const v = little ? bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24) : (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3];
|
|
22
|
+
return v >>> 0;
|
|
23
|
+
};
|
|
24
|
+
const t = u32(2);
|
|
25
|
+
if (t === null) return null;
|
|
26
|
+
const base = t & 0xffff;
|
|
27
|
+
const type = GEOM_TYPES[base % 1000];
|
|
28
|
+
if (!type) return null;
|
|
29
|
+
const hasSrid = (t & 0x20000000) !== 0;
|
|
30
|
+
const dims = 2 + ((t & 0x80000000) !== 0 ? 1 : 0) + ((t & 0x40000000) !== 0 ? 1 : 0);
|
|
31
|
+
const srid = hasSrid ? u32(10) : null;
|
|
32
|
+
return { type, srid, dims };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const RE = {
|
|
36
|
+
int: /^-?(0|[1-9]\d{0,17})$/,
|
|
37
|
+
numeric: /^-?((0|[1-9]\d{0,39})(\.\d{0,40})?|\.\d{1,40})([eE][-+]?\d{1,3})?$/,
|
|
38
|
+
bool: /^(t|f|true|false)$/i,
|
|
39
|
+
uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
|
|
40
|
+
date: /^\d{4}-\d{2}-\d{2}$/,
|
|
41
|
+
timestamp: /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(:\d{2}(\.\d+)?)?([+-]\d{2}(:?\d{2})?|Z)?$/,
|
|
42
|
+
hex: /^[0-9A-Fa-f]+$/,
|
|
43
|
+
};
|
|
44
|
+
// Du plus précis au plus général ; une valeur qui ne correspond pas élimine le type
|
|
45
|
+
const ORDER = ['bool', 'int', 'numeric', 'uuid', 'date', 'timestamp', 'binary', 'geometry', 'json', 'text'];
|
|
46
|
+
/** Une valeur au-delà de cette taille rend la colonne « lourde », quelle que soit sa part */
|
|
47
|
+
const HEAVY_VALUE = 32 * 1024;
|
|
48
|
+
|
|
49
|
+
class ColumnStats {
|
|
50
|
+
constructor(name) {
|
|
51
|
+
this.name = name;
|
|
52
|
+
this.values = 0;
|
|
53
|
+
this.nulls = 0;
|
|
54
|
+
this.bytes = 0; // octets du contenu en clair (COPY)
|
|
55
|
+
this.maxLen = 0;
|
|
56
|
+
this.sample = null;
|
|
57
|
+
this.types = new Set(ORDER);
|
|
58
|
+
this.intBig = false;
|
|
59
|
+
this.geom = null; // { type, srid, dims, points }
|
|
60
|
+
this.geomPoints = 0;
|
|
61
|
+
this.geomCount = 0;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
add(v) {
|
|
65
|
+
this.values++;
|
|
66
|
+
if (v === null) {
|
|
67
|
+
this.nulls++;
|
|
68
|
+
this.bytes += 2;
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
const len = v.length;
|
|
72
|
+
this.bytes += len + 1;
|
|
73
|
+
if (len > this.maxLen) this.maxLen = len;
|
|
74
|
+
if (this.sample === null && len) this.sample = v;
|
|
75
|
+
const t = this.types;
|
|
76
|
+
if (t.size > 1) {
|
|
77
|
+
if (t.has('bool') && !RE.bool.test(v)) t.delete('bool');
|
|
78
|
+
if (t.has('int')) {
|
|
79
|
+
if (!RE.int.test(v)) t.delete('int');
|
|
80
|
+
else if (Math.abs(Number(v)) > 2147483647) this.intBig = true;
|
|
81
|
+
}
|
|
82
|
+
if (t.has('numeric') && !RE.numeric.test(v)) t.delete('numeric');
|
|
83
|
+
if (t.has('uuid') && !RE.uuid.test(v)) t.delete('uuid');
|
|
84
|
+
if (t.has('date') && !RE.date.test(v)) t.delete('date');
|
|
85
|
+
if (t.has('timestamp') && !RE.timestamp.test(v)) t.delete('timestamp');
|
|
86
|
+
if (t.has('json') && !/^\s*[[{]/.test(v)) t.delete('json');
|
|
87
|
+
// bytea en hexadécimal (\x…) : un binaire (image, vidéo, PDF…)
|
|
88
|
+
if (t.has('binary') && !(v.startsWith('\\x') && (len - 2) % 2 === 0 && RE.hex.test(v.slice(2)))) t.delete('binary');
|
|
89
|
+
if (t.has('geometry')) {
|
|
90
|
+
const h = len >= 18 && len < 64 * 1024 * 1024 && RE.hex.test(v) ? ewkbHeader(v) : null;
|
|
91
|
+
if (!h) t.delete('geometry');
|
|
92
|
+
else {
|
|
93
|
+
if (!this.geom) this.geom = { type: h.type, srid: h.srid, dims: h.dims };
|
|
94
|
+
else if (this.geom.type !== h.type) this.geom.type = 'Geometry';
|
|
95
|
+
// Points : (octets - en-têtes) / (8 octets par coordonnée × dimensions), en gros
|
|
96
|
+
this.geomPoints += Math.max(1, Math.round((len / 2 - 9) / (8 * h.dims)));
|
|
97
|
+
this.geomCount++;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Type deviné : le plus précis qui a résisté à toutes les valeurs (vide : inconnu) */
|
|
104
|
+
type() {
|
|
105
|
+
if (this.values === this.nulls) return 'unknown';
|
|
106
|
+
for (const k of ORDER) if (this.types.has(k)) return k === 'int' && this.intBig ? 'bigint' : k;
|
|
107
|
+
return 'text';
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Octets estimés dans la base pour ce contenu (sans en-têtes de ligne) */
|
|
111
|
+
dbBytes() {
|
|
112
|
+
const filled = this.values - this.nulls;
|
|
113
|
+
const avg = filled ? (this.bytes - this.nulls * 2) / filled - 1 : 0;
|
|
114
|
+
const per = {
|
|
115
|
+
bool: 1,
|
|
116
|
+
int: 4,
|
|
117
|
+
bigint: 8,
|
|
118
|
+
numeric: Math.max(5, Math.ceil(avg / 2) + 3),
|
|
119
|
+
uuid: 16,
|
|
120
|
+
date: 4,
|
|
121
|
+
timestamp: 8,
|
|
122
|
+
geometry: avg / 2 + 8,
|
|
123
|
+
binary: (avg - 2) / 2 + 4,
|
|
124
|
+
json: avg + 4,
|
|
125
|
+
text: avg + (avg > 126 ? 4 : 1),
|
|
126
|
+
unknown: 0,
|
|
127
|
+
}[this.type()];
|
|
128
|
+
return Math.round(filled * per);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
view(totalBytes) {
|
|
132
|
+
const type = this.type();
|
|
133
|
+
const filled = this.values - this.nulls;
|
|
134
|
+
// Taille d'une valeur telle qu'elle sera stockée (un hexadécimal compte pour moitié)
|
|
135
|
+
const half = type === 'geometry' || type === 'binary';
|
|
136
|
+
const prefix = type === 'binary' ? 2 : 0; // « \x » d'un bytea
|
|
137
|
+
const avgValue = filled ? ((this.bytes - this.nulls * 2) / filled - 1 - prefix) / (half ? 2 : 1) : 0;
|
|
138
|
+
const maxValue = (this.maxLen - prefix) / (half ? 2 : 1);
|
|
139
|
+
return {
|
|
140
|
+
name: this.name,
|
|
141
|
+
type,
|
|
142
|
+
nulls: this.values ? this.nulls / this.values : 0,
|
|
143
|
+
plain_bytes: this.bytes,
|
|
144
|
+
share: totalBytes ? this.bytes / totalBytes : 0,
|
|
145
|
+
avg_value_bytes: Math.round(avgValue),
|
|
146
|
+
max_value_bytes: Math.round(maxValue),
|
|
147
|
+
heavy: (totalBytes ? this.bytes / totalBytes : 0) >= 0.5 || maxValue >= HEAVY_VALUE,
|
|
148
|
+
max_length: this.maxLen,
|
|
149
|
+
sample: this.sample === null ? null : this.sample.length > 60 ? `${this.sample.slice(0, 57)}…` : this.sample,
|
|
150
|
+
db_bytes: this.dbBytes(),
|
|
151
|
+
...(type === 'geometry' && this.geom ? { geometry: { ...this.geom, avg_points: Math.round(this.geomPoints / Math.max(1, this.geomCount)) } } : {}),
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Statistiques d'une table, alimentées ligne par ligne */
|
|
157
|
+
class TableStats {
|
|
158
|
+
constructor(target, columns) {
|
|
159
|
+
this.target = target;
|
|
160
|
+
this.columns = columns;
|
|
161
|
+
this.rows = 0;
|
|
162
|
+
this.cols = null;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
add(values) {
|
|
166
|
+
if (!this.cols) this.cols = values.map((_, i) => new ColumnStats(this.columns ? this.columns[i] : `#${i + 1}`));
|
|
167
|
+
this.rows++;
|
|
168
|
+
for (let i = 0; i < values.length; i++) this.cols[i] && this.cols[i].add(values[i]);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
view() {
|
|
172
|
+
const cols = this.cols || [];
|
|
173
|
+
const plain = cols.reduce((n, c) => n + c.bytes, 0);
|
|
174
|
+
const columns = cols.map((c) => c.view(plain));
|
|
175
|
+
// Ligne : en-tête (24 octets) + alignement ; index : clé primaire supposée (≈ 20 o/ligne), index spatial (≈ 60 o/ligne)
|
|
176
|
+
const data = columns.reduce((n, c) => n + c.db_bytes, 0) + this.rows * 28;
|
|
177
|
+
const indexes = this.rows * 20 + columns.filter((c) => c.type === 'geometry').length * this.rows * 60;
|
|
178
|
+
const heavy = columns.filter((c) => c.heavy).sort((a, b) => b.share - a.share);
|
|
179
|
+
return {
|
|
180
|
+
target: this.target,
|
|
181
|
+
named_columns: Boolean(this.columns),
|
|
182
|
+
rows: this.rows,
|
|
183
|
+
plain_bytes: plain,
|
|
184
|
+
db_bytes: Math.round((data + indexes) * 1.1),
|
|
185
|
+
columns,
|
|
186
|
+
heavy: heavy.map((c) => ({ column: c.name, share: c.share, type: c.type, max_value_bytes: c.max_value_bytes })),
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Sélection de colonnes (--fields, --exclude) : « col » s'applique à toute table qui l'a,
|
|
193
|
+
* « table.col » ou « schéma.table.col » à une seule. Renvoie pick(target, columns) ->
|
|
194
|
+
* indices gardés (null : toutes), et check() qui signale ce qui n'a rien désigné.
|
|
195
|
+
*/
|
|
196
|
+
function columnPicker({ fields, exclude } = {}) {
|
|
197
|
+
const parse = (s) =>
|
|
198
|
+
String(s || '')
|
|
199
|
+
.split(',')
|
|
200
|
+
.map((x) => x.trim())
|
|
201
|
+
.filter(Boolean);
|
|
202
|
+
const keep = parse(fields);
|
|
203
|
+
const drop = parse(exclude);
|
|
204
|
+
if (!keep.length && !drop.length) return { active: false, pick: () => null, check: () => [] };
|
|
205
|
+
if (keep.length && drop.length) throw new Error('--fields and --exclude cannot be combined: keep a list, or remove one');
|
|
206
|
+
const used = new Set();
|
|
207
|
+
const matches = (spec, target, col) => {
|
|
208
|
+
const parts = spec.split('.');
|
|
209
|
+
if (parts.length === 1) return parts[0] === col;
|
|
210
|
+
const [t, c] = [parts.slice(0, -1).join('.'), parts[parts.length - 1]];
|
|
211
|
+
return c === col && (target === t || target.endsWith(`.${t}`));
|
|
212
|
+
};
|
|
213
|
+
return {
|
|
214
|
+
active: true,
|
|
215
|
+
pick(target, columns) {
|
|
216
|
+
if (!columns) throw new Error(`${target}: the file does not name its columns (INSERT without a column list): --fields and --exclude need names`);
|
|
217
|
+
const idx = [];
|
|
218
|
+
columns.forEach((col, i) => {
|
|
219
|
+
const hitKeep = keep.find((s) => matches(s, target, col));
|
|
220
|
+
const hitDrop = drop.find((s) => matches(s, target, col));
|
|
221
|
+
if (hitKeep) used.add(hitKeep);
|
|
222
|
+
if (hitDrop) used.add(hitDrop);
|
|
223
|
+
if (keep.length ? hitKeep : !hitDrop) idx.push(i);
|
|
224
|
+
});
|
|
225
|
+
if (!idx.length) throw new Error(`${target}: no column left after --fields/--exclude`);
|
|
226
|
+
return idx.length === columns.length ? null : idx;
|
|
227
|
+
},
|
|
228
|
+
/** Ce qui n'a désigné aucune colonne (faute de frappe) */
|
|
229
|
+
check: () => [...keep, ...drop].filter((s) => !used.has(s)),
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
module.exports = { ColumnStats, TableStats, columnPicker, ewkbHeader };
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
// Paquets du magasin de seeds : contenu COPY d'une table -> gzip -> chiffré.
|
|
2
|
+
//
|
|
3
|
+
// Empreinte : sha256 du contenu COPY en clair (identité de l'objet, partagée
|
|
4
|
+
// entre branches et versions identiques d'un même projet).
|
|
5
|
+
//
|
|
6
|
+
// Chiffrement « PSD1 » (AES-256-GCM par blocs, clé de données propre à
|
|
7
|
+
// l'objet, donnée par poad.io) :
|
|
8
|
+
// "PSD1" | bloc* avec bloc = nonce(12) | longueur(u32 BE) | chiffré | étiquette(16)
|
|
9
|
+
// données associées de chaque bloc : "PSD1" | index(u32 BE) | dernier(u8)
|
|
10
|
+
// Un bloc retiré, déplacé ou ajouté après le dernier est détecté ; un fichier
|
|
11
|
+
// coupé aussi (le dernier bloc manque).
|
|
12
|
+
'use strict';
|
|
13
|
+
const crypto = require('crypto');
|
|
14
|
+
const fs = require('fs');
|
|
15
|
+
const path = require('path');
|
|
16
|
+
const zlib = require('zlib');
|
|
17
|
+
const { Transform } = require('stream');
|
|
18
|
+
|
|
19
|
+
const MAGIC = Buffer.from('PSD1');
|
|
20
|
+
const CHUNK = 1024 * 1024;
|
|
21
|
+
|
|
22
|
+
/** Contenu COPY d'une table, écrit compressé dans un fichier, empreinte en route */
|
|
23
|
+
class TableSink {
|
|
24
|
+
constructor(file) {
|
|
25
|
+
this.file = file;
|
|
26
|
+
this.hash = crypto.createHash('sha256');
|
|
27
|
+
this.plainBytes = 0;
|
|
28
|
+
this.rows = 0;
|
|
29
|
+
this.pending = [];
|
|
30
|
+
this.pendingBytes = 0;
|
|
31
|
+
this.gzip = zlib.createGzip({ level: 6 });
|
|
32
|
+
this.out = fs.createWriteStream(file);
|
|
33
|
+
this.gzip.pipe(this.out);
|
|
34
|
+
this.done = new Promise((resolve, reject) => {
|
|
35
|
+
this.out.on('finish', resolve);
|
|
36
|
+
this.out.on('error', reject);
|
|
37
|
+
this.gzip.on('error', reject);
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
row(line) {
|
|
42
|
+
const b = line + '\n';
|
|
43
|
+
this.pending.push(b);
|
|
44
|
+
this.pendingBytes += b.length;
|
|
45
|
+
this.rows++;
|
|
46
|
+
if (this.pendingBytes >= 256 * 1024) this.flushSync();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
flushSync() {
|
|
50
|
+
if (!this.pending.length) return true;
|
|
51
|
+
const buf = Buffer.from(this.pending.join(''), 'utf8');
|
|
52
|
+
this.pending = [];
|
|
53
|
+
this.pendingBytes = 0;
|
|
54
|
+
this.hash.update(buf);
|
|
55
|
+
this.plainBytes += buf.length;
|
|
56
|
+
return this.gzip.write(buf);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Attend que la compression ait absorbé ce qui a été écrit */
|
|
60
|
+
async drain() {
|
|
61
|
+
if (!this.flushSync()) await new Promise((r) => this.gzip.once('drain', r));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async close() {
|
|
65
|
+
this.flushSync();
|
|
66
|
+
this.gzip.end();
|
|
67
|
+
await this.done;
|
|
68
|
+
return { sha256: this.hash.digest('hex'), plainBytes: this.plainBytes, rows: this.rows, file: this.file, gzBytes: fs.statSync(this.file).size };
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const aad = (index, last) => {
|
|
73
|
+
const b = Buffer.alloc(9);
|
|
74
|
+
MAGIC.copy(b, 0);
|
|
75
|
+
b.writeUInt32BE(index, 4);
|
|
76
|
+
b.writeUInt8(last ? 1 : 0, 8);
|
|
77
|
+
return b;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
/** Chiffre un fichier (le gzip d'une table) vers out ; renvoie la taille écrite */
|
|
81
|
+
async function encryptFile(src, out, key) {
|
|
82
|
+
if (key.length !== 32) throw new Error('data key must be 32 bytes');
|
|
83
|
+
const size = fs.statSync(src).size;
|
|
84
|
+
const fd = fs.openSync(src, 'r');
|
|
85
|
+
const w = fs.createWriteStream(out);
|
|
86
|
+
const write = (b) => (w.write(b) ? null : new Promise((r) => w.once('drain', r)));
|
|
87
|
+
try {
|
|
88
|
+
await write(MAGIC);
|
|
89
|
+
const count = Math.max(1, Math.ceil(size / CHUNK));
|
|
90
|
+
const buf = Buffer.alloc(CHUNK);
|
|
91
|
+
for (let index = 0; index < count; index++) {
|
|
92
|
+
const n = fs.readSync(fd, buf, 0, CHUNK, index * CHUNK);
|
|
93
|
+
const nonce = crypto.randomBytes(12);
|
|
94
|
+
const c = crypto.createCipheriv('aes-256-gcm', key, nonce);
|
|
95
|
+
c.setAAD(aad(index, index === count - 1));
|
|
96
|
+
const ct = Buffer.concat([c.update(buf.subarray(0, n)), c.final()]);
|
|
97
|
+
const len = Buffer.alloc(4);
|
|
98
|
+
len.writeUInt32BE(ct.length);
|
|
99
|
+
const p = write(Buffer.concat([nonce, len, ct, c.getAuthTag()]));
|
|
100
|
+
if (p) await p;
|
|
101
|
+
}
|
|
102
|
+
} finally {
|
|
103
|
+
fs.closeSync(fd);
|
|
104
|
+
await new Promise((resolve, reject) => w.end((e) => (e ? reject(e) : resolve())));
|
|
105
|
+
}
|
|
106
|
+
return fs.statSync(out).size;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Flux de déchiffrement PSD1 (sortie : le gzip en clair) */
|
|
110
|
+
function decryptStream(key) {
|
|
111
|
+
let buf = Buffer.alloc(0);
|
|
112
|
+
let magic = false;
|
|
113
|
+
let index = 0;
|
|
114
|
+
/** Taille du bloc en tête de buf s'il est complet, sinon 0 */
|
|
115
|
+
const complete = () => {
|
|
116
|
+
if (buf.length < 16) return 0;
|
|
117
|
+
const len = buf.readUInt32BE(12);
|
|
118
|
+
if (len > CHUNK + 16) throw new Error('corrupted seed object (block too large)');
|
|
119
|
+
return buf.length >= 32 + len ? 32 + len : 0;
|
|
120
|
+
};
|
|
121
|
+
const open = (total, last) => {
|
|
122
|
+
const nonce = buf.subarray(0, 12);
|
|
123
|
+
const ct = buf.subarray(16, total - 16);
|
|
124
|
+
const tag = buf.subarray(total - 16, total);
|
|
125
|
+
const d = crypto.createDecipheriv('aes-256-gcm', key, nonce);
|
|
126
|
+
d.setAAD(aad(index, last));
|
|
127
|
+
d.setAuthTag(tag);
|
|
128
|
+
let plain;
|
|
129
|
+
try {
|
|
130
|
+
plain = Buffer.concat([d.update(ct), d.final()]);
|
|
131
|
+
} catch {
|
|
132
|
+
throw new Error(last ? 'seed object is truncated or was altered' : 'seed object was altered (authentication failed)');
|
|
133
|
+
}
|
|
134
|
+
buf = buf.subarray(total);
|
|
135
|
+
index++;
|
|
136
|
+
return plain;
|
|
137
|
+
};
|
|
138
|
+
const header = () => {
|
|
139
|
+
if (magic || buf.length < 4) return;
|
|
140
|
+
if (!buf.subarray(0, 4).equals(MAGIC)) throw new Error('not a poad seed object (bad header)');
|
|
141
|
+
buf = buf.subarray(4);
|
|
142
|
+
magic = true;
|
|
143
|
+
};
|
|
144
|
+
// Un bloc n'est déchiffré « non dernier » que si d'autres octets le suivent ; le dernier l'est à la fin du flux
|
|
145
|
+
return new Transform({
|
|
146
|
+
transform(chunk, _enc, cb) {
|
|
147
|
+
buf = buf.length ? Buffer.concat([buf, chunk]) : chunk;
|
|
148
|
+
try {
|
|
149
|
+
header();
|
|
150
|
+
if (magic) {
|
|
151
|
+
for (let total = complete(); total && buf.length > total; total = complete()) this.push(open(total, false));
|
|
152
|
+
}
|
|
153
|
+
cb();
|
|
154
|
+
} catch (e) {
|
|
155
|
+
cb(e);
|
|
156
|
+
}
|
|
157
|
+
},
|
|
158
|
+
flush(cb) {
|
|
159
|
+
try {
|
|
160
|
+
header();
|
|
161
|
+
const total = magic ? complete() : 0;
|
|
162
|
+
if (!total || buf.length !== total) throw new Error('seed object is truncated (no final block)');
|
|
163
|
+
this.push(open(total, true));
|
|
164
|
+
cb();
|
|
165
|
+
} catch (e) {
|
|
166
|
+
cb(e);
|
|
167
|
+
}
|
|
168
|
+
},
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Fichier temporaire d'un envoi */
|
|
173
|
+
function tmpDir() {
|
|
174
|
+
const base = path.join(require('os').homedir(), '.poad', 'cache', 'seeds', 'tmp');
|
|
175
|
+
fs.mkdirSync(base, { recursive: true, mode: 0o700 });
|
|
176
|
+
return fs.mkdtempSync(path.join(base, 'push-'));
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
module.exports = { TableSink, encryptFile, decryptStream, tmpDir, MAGIC, CHUNK };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// Affichage d'une inspection (poad seed inspect, et résumé de poad seed push)
|
|
2
|
+
'use strict';
|
|
3
|
+
const fmt = (n) => (n >= 1024 ** 3 ? `${(n / 1024 ** 3).toFixed(2)} GB` : n >= 1024 ** 2 ? `${(n / 1024 ** 2).toFixed(1)} MB` : n >= 1024 ? `${Math.round(n / 1024)} KB` : `${n} B`);
|
|
4
|
+
const pct = (x) => (x >= 0.995 ? '100 %' : x < 0.005 && x > 0 ? '<1 %' : `${Math.round(x * 100)} %`);
|
|
5
|
+
const pad = (s, n) => {
|
|
6
|
+
const t = String(s);
|
|
7
|
+
return t.length >= n ? t : t + ' '.repeat(n - t.length);
|
|
8
|
+
};
|
|
9
|
+
const lpad = (s, n) => {
|
|
10
|
+
const t = String(s);
|
|
11
|
+
return t.length >= n ? t : ' '.repeat(n - t.length) + t;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
/** Lignes d'une table inspectée (sans couleur si chalk absent) */
|
|
15
|
+
function tableReport(st, chalk, { dropped = [] } = {}) {
|
|
16
|
+
const c = chalk || { bold: (x) => x, grey: (x) => x, yellowBright: (x) => x, cyanBright: (x) => x };
|
|
17
|
+
const out = [];
|
|
18
|
+
out.push(`${c.bold(st.target)} ${st.rows.toLocaleString('en-US')} rows ${fmt(st.plain_bytes)} as text ≈ ${fmt(st.db_bytes)} in the database`);
|
|
19
|
+
if (dropped.length) out.push(c.grey(` left out: ${dropped.join(', ')}`));
|
|
20
|
+
const w = Math.max(6, ...st.columns.map((x) => x.name.length)) + 2;
|
|
21
|
+
out.push(c.grey(` ${pad('column', w)}${pad('type', 11)}${lpad('empty', 7)}${lpad('volume', 9)}${lpad('avg value', 12)}${lpad('max value', 12)} sample`));
|
|
22
|
+
for (const col of st.columns) {
|
|
23
|
+
const extra = col.geometry ? ` ${col.geometry.type}${col.geometry.srid ? `, SRID ${col.geometry.srid}` : ''}, ~${col.geometry.avg_points} points` : '';
|
|
24
|
+
const sample = col.type === 'binary' || col.type === 'geometry' ? extra.trim() : col.sample === null ? '' : JSON.stringify(col.sample);
|
|
25
|
+
const line = ` ${pad(col.name, w)}${pad(col.type, 11)}${lpad(pct(col.nulls), 7)}${lpad(pct(col.share), 9)}${lpad(fmt(col.avg_value_bytes), 12)}${lpad(fmt(col.max_value_bytes), 12)} ${sample}`;
|
|
26
|
+
out.push(col.heavy ? c.yellowBright(line) : line);
|
|
27
|
+
}
|
|
28
|
+
if (st.heavy.length) {
|
|
29
|
+
const names = st.heavy.map((h) => h.column);
|
|
30
|
+
out.push(c.yellowBright(` ⚠ heavy: ${st.heavy.map((h) => `${h.column} (${pct(h.share)} of the volume, up to ${fmt(h.max_value_bytes)} per value)`).join(', ')}`));
|
|
31
|
+
out.push(c.grey(` leave it out: --exclude ${names.join(',')} or keep only what you need: --fields <a,b,…>`));
|
|
32
|
+
}
|
|
33
|
+
if (!st.named_columns) out.push(c.grey(' The file does not name its columns (INSERT without a column list): --fields and --exclude are not available.'));
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
module.exports = { tableReport, fmt, pct };
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
// poad seed : conversion d'un fichier, envoi au magasin de poad.io (URL
|
|
2
|
+
// signées), chargement (hébergé : par poad.io ; local : dans l'engine Docker).
|
|
3
|
+
'use strict';
|
|
4
|
+
const fs = require('fs');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const zlib = require('zlib');
|
|
7
|
+
const { pipeline } = require('stream/promises');
|
|
8
|
+
const { spawn } = require('child_process');
|
|
9
|
+
const api = require('../cloud/api');
|
|
10
|
+
const { SqlSource, CsvSource, parseTarget } = require('./convert');
|
|
11
|
+
const { TableSink, encryptFile, decryptStream, tmpDir } = require('./pack');
|
|
12
|
+
const A = require('./apply');
|
|
13
|
+
|
|
14
|
+
const fmt = (n) => (n >= 1024 ** 3 ? `${(n / 1024 ** 3).toFixed(2)} GB` : n >= 1024 ** 2 ? `${(n / 1024 ** 2).toFixed(1)} MB` : `${Math.max(1, Math.round(n / 1024))} KB`);
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Fichier -> une entrée par table : { target, columns, rows, sha256, plainBytes, file (gzip), stats }.
|
|
18
|
+
* format : sql | csv (sinon d'après l'extension) ; table : obligatoire en CSV (sinon le nom du fichier).
|
|
19
|
+
* fields / exclude : colonnes gardées ou écartées (voir inspect.columnPicker).
|
|
20
|
+
* write: false : inspection seule (rien n'est écrit) ; les statistiques sont toujours calculées.
|
|
21
|
+
*/
|
|
22
|
+
async function convertFile(file, { format, table, dir, onProgress, fields, exclude, write = true } = {}) {
|
|
23
|
+
const { TableStats, columnPicker } = require('./inspect');
|
|
24
|
+
const { copyEscape } = require('./convert');
|
|
25
|
+
const ext = path.extname(file).toLowerCase();
|
|
26
|
+
const kind = format || (ext === '.csv' || ext === '.tsv' ? 'csv' : ext === '.sql' ? 'sql' : null);
|
|
27
|
+
if (!kind) throw api.usageError(`${path.basename(file)}: unknown format (.sql or .csv), or pass --format sql|csv`);
|
|
28
|
+
let picker;
|
|
29
|
+
try {
|
|
30
|
+
picker = columnPicker({ fields, exclude });
|
|
31
|
+
} catch (e) {
|
|
32
|
+
throw api.usageError(e.message);
|
|
33
|
+
}
|
|
34
|
+
// Par table : colonnes d'origine, indices gardés, colonnes gardées, statistiques, fichier
|
|
35
|
+
const tablesBy = new Map();
|
|
36
|
+
const onRow = (target, cols, values) => {
|
|
37
|
+
let t = tablesBy.get(target);
|
|
38
|
+
if (!t) {
|
|
39
|
+
let keep = null;
|
|
40
|
+
try {
|
|
41
|
+
keep = picker.pick(target, cols);
|
|
42
|
+
} catch (e) {
|
|
43
|
+
throw api.usageError(e.message);
|
|
44
|
+
}
|
|
45
|
+
const kept = cols && keep ? keep.map((i) => cols[i]) : cols;
|
|
46
|
+
t = { cols, keep, kept, stats: new TableStats(target, kept), sink: write ? new TableSink(path.join(dir, `${tablesBy.size}.copy.gz`)) : null };
|
|
47
|
+
tablesBy.set(target, t);
|
|
48
|
+
} else if (JSON.stringify(t.cols) !== JSON.stringify(cols)) {
|
|
49
|
+
throw api.usageError(`${target}: rows with different column lists in the same file (split the file, or give every INSERT the same columns)`);
|
|
50
|
+
}
|
|
51
|
+
const v = t.keep ? t.keep.map((i) => values[i]) : values;
|
|
52
|
+
t.stats.add(v);
|
|
53
|
+
if (t.sink) t.sink.row(v.map(copyEscape).join('\t'));
|
|
54
|
+
};
|
|
55
|
+
const sinks = { values: () => [...tablesBy.values()].map((t) => t.sink).filter(Boolean) };
|
|
56
|
+
let source;
|
|
57
|
+
if (kind === 'csv') {
|
|
58
|
+
const target = table ? parseTarget(table) : parseTarget(path.basename(file, path.extname(file)));
|
|
59
|
+
if (!target) throw api.usageError('CSV: give the target table with --table schema.table');
|
|
60
|
+
source = new CsvSource({ target, onRow });
|
|
61
|
+
} else source = new SqlSource({ onRow });
|
|
62
|
+
const total = fs.statSync(file).size;
|
|
63
|
+
let read = 0;
|
|
64
|
+
const rs = fs.createReadStream(file, { encoding: 'utf8', highWaterMark: 1 << 20 });
|
|
65
|
+
for await (const chunk of rs) {
|
|
66
|
+
source.push(chunk);
|
|
67
|
+
read = rs.bytesRead;
|
|
68
|
+
for (const s of sinks.values()) await s.drain();
|
|
69
|
+
onProgress && onProgress(read, total);
|
|
70
|
+
}
|
|
71
|
+
source.end();
|
|
72
|
+
const unused = picker.check();
|
|
73
|
+
if (unused.length) throw api.usageError(`--fields/--exclude: no column matches ${unused.join(', ')}`);
|
|
74
|
+
const tables = [];
|
|
75
|
+
for (const [target, t] of tablesBy) {
|
|
76
|
+
const r = t.sink ? await t.sink.close() : null;
|
|
77
|
+
tables.push({ target, columns: t.kept, rows: t.stats.rows, sha256: r && r.sha256, plainBytes: r && r.plainBytes, file: r && r.file, stats: t.stats.view(), dropped: t.cols && t.keep ? t.cols.filter((_, i) => !t.keep.includes(i)) : [] });
|
|
78
|
+
}
|
|
79
|
+
// Une seule table en SQL et --table donné : il la renomme
|
|
80
|
+
if (kind === 'sql' && table) {
|
|
81
|
+
const t = parseTarget(table);
|
|
82
|
+
if (!t) throw api.usageError(`--table: "${table}" is not schema.table`);
|
|
83
|
+
if (tables.length !== 1) throw api.usageError(`--table renames a single table; the file has ${tables.length}: ${tables.map((x) => x.target).join(', ')}`);
|
|
84
|
+
tables[0].target = t;
|
|
85
|
+
tables[0].stats.target = t;
|
|
86
|
+
}
|
|
87
|
+
return { tables, skipped: source.skipped || {}, mutations: source.mutations || 0 };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Envoie une table convertie ; renvoie la réponse de commit */
|
|
91
|
+
async function pushTable(id, t, { mode, source, onProgress }) {
|
|
92
|
+
const key = (k) => Buffer.from(k, 'base64');
|
|
93
|
+
const enc = `${t.file}.psd`;
|
|
94
|
+
// Taille chiffrée connue avant la clé : même découpage, taille déterministe
|
|
95
|
+
const gz = fs.statSync(t.file).size;
|
|
96
|
+
const blocks = Math.max(1, Math.ceil(gz / (1024 * 1024)));
|
|
97
|
+
const stored = 4 + gz + blocks * 32;
|
|
98
|
+
const prep = await api.call('POST', `v1/projects/${api.enc(id)}/seeds/upload`, {
|
|
99
|
+
body: { target: t.target, sha256: t.sha256, plain_bytes: t.plainBytes, stored_bytes: stored },
|
|
100
|
+
what: `seed ${t.target}`,
|
|
101
|
+
});
|
|
102
|
+
// Ce que l'inspection a mesuré part avec le seed (jamais de valeur des données : pas d'exemple)
|
|
103
|
+
const stats = t.stats ? t.stats.columns.map(({ name, type, share, avg_value_bytes, max_value_bytes, nulls, heavy }) => ({ name, type, share, avg_value_bytes, max_value_bytes, nulls, heavy })) : undefined;
|
|
104
|
+
let commit = { target: t.target, sha256: t.sha256, mode, rows: t.rows, columns: t.columns, source, db_bytes: t.stats ? t.stats.db_bytes : undefined, stats, dropped: t.dropped };
|
|
105
|
+
if (!prep.exists) {
|
|
106
|
+
const written = await encryptFile(t.file, enc, key(prep.key));
|
|
107
|
+
if (written !== stored) throw new api.CloudError(`internal: encrypted size ${written} differs from ${stored}`);
|
|
108
|
+
if (prep.upload.kind === 'single') {
|
|
109
|
+
await putWithRetry(prep.upload.url, fs.readFileSync(enc));
|
|
110
|
+
onProgress && onProgress(stored, stored);
|
|
111
|
+
} else {
|
|
112
|
+
const { part_size: size, urls, upload_id: uploadId } = prep.upload;
|
|
113
|
+
const parts = [];
|
|
114
|
+
const fd = fs.openSync(enc, 'r');
|
|
115
|
+
try {
|
|
116
|
+
for (let i = 0; i < urls.length; i++) {
|
|
117
|
+
const len = Math.min(size, stored - i * size);
|
|
118
|
+
const buf = Buffer.alloc(len);
|
|
119
|
+
fs.readSync(fd, buf, 0, len, i * size);
|
|
120
|
+
const etag = await putWithRetry(urls[i], buf);
|
|
121
|
+
parts.push({ n: i + 1, etag });
|
|
122
|
+
onProgress && onProgress(Math.min(stored, (i + 1) * size), stored);
|
|
123
|
+
}
|
|
124
|
+
} finally {
|
|
125
|
+
fs.closeSync(fd);
|
|
126
|
+
}
|
|
127
|
+
commit = { ...commit, upload_id: uploadId, parts };
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
const r = await api.call('POST', `v1/projects/${api.enc(id)}/seeds/commit`, { body: commit, what: `seed ${t.target}`, timeout: 120000 });
|
|
131
|
+
return { ...r, uploaded: !prep.exists, stored };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function putWithRetry(url, buf, tries = 3) {
|
|
135
|
+
let last;
|
|
136
|
+
for (let i = 0; i < tries; i++) {
|
|
137
|
+
try {
|
|
138
|
+
const res = await fetch(url, { method: 'PUT', body: buf, headers: { 'content-type': 'application/octet-stream' }, signal: AbortSignal.timeout(15 * 60 * 1000) });
|
|
139
|
+
if (res.ok) return res.headers.get('etag') || '';
|
|
140
|
+
last = new Error(`storage refused the upload (HTTP ${res.status})`);
|
|
141
|
+
if (res.status < 500) break;
|
|
142
|
+
} catch (e) {
|
|
143
|
+
last = e;
|
|
144
|
+
}
|
|
145
|
+
await new Promise((r) => setTimeout(r, 1000 * (i + 1)));
|
|
146
|
+
}
|
|
147
|
+
throw new api.CloudError(`Upload failed: ${last && last.message}`, { code: 'seed_upload_failed' });
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Attend la fin d'un chargement hébergé ; onStep à chaque changement */
|
|
151
|
+
async function waitLoad(id, loadId, { onStep, interval = 2000, timeout = 60 * 60 * 1000 } = {}) {
|
|
152
|
+
const until = Date.now() + timeout;
|
|
153
|
+
let seen = '';
|
|
154
|
+
for (;;) {
|
|
155
|
+
const l = await api.call('GET', `v1/projects/${api.enc(id)}/seeds/loads/${api.enc(loadId)}`, { what: 'seed load' });
|
|
156
|
+
const sig = JSON.stringify(l.steps.map((s) => s.status));
|
|
157
|
+
if (sig !== seen) {
|
|
158
|
+
seen = sig;
|
|
159
|
+
onStep && onStep(l);
|
|
160
|
+
}
|
|
161
|
+
if (l.status !== 'running') return l;
|
|
162
|
+
if (Date.now() > until) throw new api.CloudError('Still loading after an hour: "poad seed ls" shows the progress.', { code: 'timeout' });
|
|
163
|
+
await new Promise((r) => setTimeout(r, interval));
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** psql dans l'engine local (Docker), script sur l'entrée standard */
|
|
168
|
+
function localPsql(container, extra = [], database = 'postgres') {
|
|
169
|
+
return spawn('docker', ['exec', '-i', container, 'psql', '-X', '-q', '-v', 'VERBOSITY=verbose', '-U', 'postgres', '-h', '/var/run/postgresql', '-d', database, ...extra], { stdio: ['pipe', 'pipe', 'pipe'] });
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Charge un seed (téléchargé de poad.io) dans l'engine local ; { written, deleted } */
|
|
173
|
+
async function loadLocal(container, d, { database } = {}) {
|
|
174
|
+
const res = await fetch(d.url, { signal: AbortSignal.timeout(60 * 60 * 1000) });
|
|
175
|
+
if (!res.ok) throw new api.CloudError(`${d.target}: download refused (HTTP ${res.status})`, { code: 'seed_download_failed' });
|
|
176
|
+
const { Readable } = require('stream');
|
|
177
|
+
const c = localPsql(container, [], database);
|
|
178
|
+
let out = '';
|
|
179
|
+
c.stdout.on('data', (x) => (out = (out + x).slice(-20000)));
|
|
180
|
+
c.stderr.on('data', (x) => (out = (out + x).slice(-20000)));
|
|
181
|
+
const closed = new Promise((r) => c.on('close', r));
|
|
182
|
+
c.stdin.on('error', () => {});
|
|
183
|
+
c.stdin.write(A.head(d.target, d.columns));
|
|
184
|
+
// psql peut s'arrêter avant la fin (ON_ERROR_STOP) : c'est alors son message qui compte, pas l'écriture coupée
|
|
185
|
+
let streamErr = null;
|
|
186
|
+
await pipeline(Readable.fromWeb(res.body), decryptStream(Buffer.from(d.key, 'base64')), zlib.createGunzip(), c.stdin, { end: false })
|
|
187
|
+
.then(() => c.stdin.end(A.tail(d.target, d.columns)))
|
|
188
|
+
.catch((e) => {
|
|
189
|
+
streamErr = e;
|
|
190
|
+
c.stdin.destroy();
|
|
191
|
+
});
|
|
192
|
+
const code = await closed;
|
|
193
|
+
if (code === 0 && streamErr) throw new api.CloudError(`${d.target}: ${streamErr.message}`, { code: 'seed_load_failed' });
|
|
194
|
+
if (code !== 0) {
|
|
195
|
+
const lines = out.split('\n');
|
|
196
|
+
const e = (lines.find((l) => /ERROR:/.test(l)) || lines.filter(Boolean).pop() || `psql ${code}`).replace(/^psql:[^E]*/, '').replace(/^ERROR:\s+([0-9A-Z]{5}:\s+)?/, '');
|
|
197
|
+
const detail = lines.find((l) => /^DETAIL:/.test(l));
|
|
198
|
+
throw new api.CloudError(`${d.target}: ${e}${detail ? ` — ${detail.replace(/^DETAIL:\s+/, '')}` : ''}`, { code: 'seed_load_failed' });
|
|
199
|
+
}
|
|
200
|
+
return A.parseNotice(out) || { written: null, deleted: null };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Dépendances entre tables de l'engine local (ordre de chargement) */
|
|
204
|
+
function localEdges(container) {
|
|
205
|
+
return new Promise((resolve) => {
|
|
206
|
+
const c = localPsql(container, ['-tA', '-c', A.FK_SQL]);
|
|
207
|
+
let out = '';
|
|
208
|
+
c.stdout.on('data', (x) => (out += x));
|
|
209
|
+
c.on('close', (code) => resolve(code === 0 ? out.split('\n').filter(Boolean) : []));
|
|
210
|
+
c.stdin.end();
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
module.exports = { convertFile, pushTable, waitLoad, loadLocal, localEdges, fmt, tmpDir };
|