/
importpg.go
488 lines (452 loc) · 13 KB
/
importpg.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
package main
import (
"context"
"fmt"
"time"
"github.com/ipfs/go-cid"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/urfave/cli/v2"
"golang.org/x/xerrors"
)
const (
dagQueryTimeout = time.Duration(12 * time.Hour)
nftsUploadAuthkeyFkColumn = `key_id`
nftsDetailsUpload = `
JSONB_STRIP_NULLS( JSONB_BUILD_OBJECT(
'original_cid', ds.source_cid,
'mime_type', CASE WHEN ds.mime_type = '' THEN NULL ELSE ds.mime_type END,
'upload_type', ds.type,
'label', CASE WHEN ds.name = '' THEN NULL ELSE ds.name END,
'files', CASE WHEN ds.files = JSONB('[]') THEN NULL ELSE ds.files END,
'origins', ds.origins,
'meta', ds.meta,
'token_used', CASE WHEN ds.key_id IS NULL THEN NULL ELSE JSONB_BUILD_OBJECT(
'id', ds.key_id,
'label', k.name
) END,
'pin_reported_at', (
SELECT MIN(p.updated_at)
FROM pin p
WHERE
p.content_cid = d.cid
AND
p.status = 'Pinned'
AND
p.service != 'Pinata'
)
) )
`
w3sUploadAuthkeyFkColumn = `auth_key_id`
w3sDetailsUpload = `
JSONB_STRIP_NULLS( JSONB_BUILD_OBJECT(
'original_cid', ds.source_cid,
'upload_type', ds.type,
'label', CASE WHEN ds.name = '' THEN NULL ELSE ds.name END,
'token_used', CASE WHEN ds.auth_key_id IS NULL THEN NULL ELSE JSONB_BUILD_OBJECT(
'id', ds.auth_key_id,
'label', k.name
) END,
'pin_reported_at', (
SELECT MIN(p.updated_at)
FROM pin p
WHERE
p.content_cid = d.cid
AND
p.status = 'Pinned'
)
) )
`
w3sPsaUnion = `UNION ALL (
SELECT
k.user_id::TEXT AS source_label,
d.cid AS cid_v1,
ds.id AS source_key,
d.dag_size AS size_claimed,
ds.inserted_at AS entry_created,
ds.deleted_at AS entry_removed,
GREATEST(
ds.updated_at
-- (
-- SELECT MAX(p.updated_at)
-- FROM pin p
-- WHERE
-- p.content_cid = d.cid
-- )
) AS entry_last_updated,
JSONB_STRIP_NULLS( JSONB_BUILD_OBJECT(
'original_cid', ds.source_cid,
'upload_type', 'Remote',
'label', CASE WHEN ds.name = '' THEN NULL ELSE ds.name END,
'token_used', JSONB_BUILD_OBJECT(
'id', ds.auth_key_id,
'label', k.name
),
'origins', ds.origins,
'meta', ds.meta,
'pin_reported_at', (
SELECT MIN(p.updated_at)
FROM pin p
WHERE
p.content_cid = d.cid
AND
p.status = 'Pinned'
)
) ) AS details
FROM psa_pin_request ds
JOIN content d ON ds.content_cid = d.cid
JOIN auth_key k ON ds.auth_key_id = k.id
WHERE
ds.updated_at > $1
-- OR
-- d.cid IN ( SELECT cid FROM cids_with_pin_updates )
)`
nftsDetailsUser = `
JSONB_STRIP_NULLS( JSONB_BUILD_OBJECT(
'public_address', s.public_address, -- FIXME should go away, same as magic_link_id
'github_id', NULLIF( COALESCE( s.github->>'userHandle', SUBSTRING( s.github_id, 'github\|([0-9]+)') ), '' )::BIGINT,
'email', s.email,
'magic_link_id', CASE WHEN s.magic_link_id = '' THEN NULL ELSE s.magic_link_id END,
'name', CASE WHEN s.name = '' THEN NULL ELSE s.name END,
'nickname', SUBSTRING( s.github->'userInfo'->>'profile', '([^/]+)$' ),
'picture', CASE WHEN s.picture = '' THEN NULL ELSE s.picture END
) )
`
w3sDetailsUser = `
JSONB_STRIP_NULLS( JSONB_BUILD_OBJECT(
'public_address', s.public_address, -- FIXME should go away, same as magic_link_id
'github_id', NULLIF( s.github, '' )::BIGINT,
'email', s.email,
'magic_link_id', CASE WHEN s.issuer = '' THEN NULL ELSE s.issuer END,
'name', CASE WHEN s.name = '' THEN NULL ELSE s.name END,
'picture', CASE WHEN s.picture = '' THEN NULL ELSE s.picture END
) )
`
)
type pgProject struct {
id int
label string
pgConnString string
templatedSQLDetailsUser string
templatedSQLDetailsUpload string
templatedSQLUploadAuthkeyFkColumn string
templatedSQLPsaUnion string
}
var pgProjects = []pgProject{
{
id: 0,
label: "web3.storage-stage",
pgConnString: "service=web3-storage-stage-ro",
templatedSQLDetailsUser: w3sDetailsUser,
templatedSQLUploadAuthkeyFkColumn: w3sUploadAuthkeyFkColumn,
templatedSQLDetailsUpload: w3sDetailsUpload,
templatedSQLPsaUnion: w3sPsaUnion,
},
{
id: 1,
label: "web3.storage-prod",
pgConnString: "service=web3-storage-ro",
templatedSQLDetailsUser: w3sDetailsUser,
templatedSQLUploadAuthkeyFkColumn: w3sUploadAuthkeyFkColumn,
templatedSQLDetailsUpload: w3sDetailsUpload,
templatedSQLPsaUnion: w3sPsaUnion,
},
{
id: 2,
label: "nft.storage-prod",
pgConnString: "service=nft-storage-ro",
templatedSQLDetailsUser: nftsDetailsUser,
templatedSQLUploadAuthkeyFkColumn: nftsUploadAuthkeyFkColumn,
templatedSQLDetailsUpload: nftsDetailsUpload,
},
}
func getPgDags(cctx *cli.Context, p pgProject, cutoff time.Time, knownDags, ownAggregates map[cid.Cid]struct{}) error {
ctx, closer := context.WithCancel(cctx.Context)
defer closer()
remoteDags := make(map[[2]string]*dagSourceEntry, 1<<20)
var totalQueriedDags, existingDags, newSources, newDags, removedDags int
defer func() {
log.Infow("summary",
"project", p.label,
"existingDags", existingDags,
"queryPeriodSince", cutoff,
"totalQueryPeriodDags", totalQueriedDags,
"totalUpsertedDags", len(remoteDags),
"newSources", newSources,
"newDags", newDags,
"removedDags", removedDags,
)
}()
projPrefix := fmt.Sprintf("project %s (%d)", p.label, p.id)
srcDbConn, err := pgxpool.ParseConfig(p.pgConnString)
if err != nil {
return err
}
srcDb, err := pgxpool.ConnectConfig(ctx, srcDbConn)
if err != nil {
return err
}
defer srcDb.Close()
srcTx, err := srcDb.BeginTx(ctx, pgx.TxOptions{AccessMode: pgx.ReadOnly})
if err != nil {
return err
}
defer srcTx.Rollback(context.Background()) //nolint:errcheck
_, err = srcTx.Exec(ctx, fmt.Sprintf(`SET LOCAL statement_timeout = %d`, dagQueryTimeout.Milliseconds()))
if err != nil {
return err
}
// first pull all dag rows, store in ram, users come second
dagRows, err := srcTx.Query(
ctx,
fmt.Sprintf(
`
-- WITH
-- cids_with_pin_updates AS (
-- SELECT DISTINCT(pin.content_cid) FROM pin WHERE pin.updated_at > $1
-- )
(
SELECT
ds.user_id::TEXT AS source_label,
d.cid AS cid_v1,
ds.source_cid AS source_key,
d.dag_size AS size_claimed,
ds.inserted_at AS entry_created,
ds.deleted_at AS entry_removed,
GREATEST(
ds.updated_at
-- (
-- SELECT MAX(p.updated_at)
-- FROM pin p
-- WHERE
-- p.content_cid = d.cid
-- )
) AS entry_last_updated,
%s AS details
FROM upload ds
JOIN content d ON ds.content_cid = d.cid
LEFT JOIN auth_key k ON ds.%s = k.id
WHERE
ds.updated_at > $1
-- OR
-- d.cid IN ( SELECT cid FROM cids_with_pin_updates )
)
%s
`,
p.templatedSQLDetailsUpload,
p.templatedSQLUploadAuthkeyFkColumn,
p.templatedSQLPsaUnion,
),
cutoff,
)
if err != nil {
return xerrors.Errorf("Pg error: %w", err)
}
defer dagRows.Close()
earliestDagUpdate := time.Now()
for dagRows.Next() {
var e dagSourceEntry
if err = dagRows.Scan(&e.sourceLabel, &e.CidV1Str, &e.SourceKey, &e.SizeClaimed, &e.CreatedAt, &e.RemovedAt, &e.UpdatedAt, &e.Details); err != nil {
return xerrors.Errorf("Pg error: %w", err)
}
c, err := cid.Parse(e.CidV1Str)
if err != nil {
return err
}
e.cidV1 = cidv1(c)
// why would anyone be so mean?
if _, own := ownAggregates[e.cidV1]; own {
continue
}
totalQueriedDags++
remoteDags[[2]string{e.sourceLabel, e.SourceKey}] = &e
if earliestDagUpdate.After(e.UpdatedAt) {
earliestDagUpdate = e.UpdatedAt
}
}
if err = dagRows.Err(); err != nil {
return xerrors.Errorf("Pg error: %w", err)
}
dagRows.Close()
log.Infof("%s: retrieved %d remote dag entries for processing", projPrefix, len(remoteDags))
// Check for which already-existing records can we skip an upsert
dagentryRows, err := cargoDb.Query(
ctx,
`
SELECT s.source_label, ds.source_key, ds.entry_last_updated
FROM cargo.dag_sources ds
JOIN cargo.sources s USING ( srcid )
WHERE
s.project = $1
AND
ds.entry_last_updated >= $2
`,
p.id,
earliestDagUpdate,
)
if err != nil {
return xerrors.Errorf("Pg error: %w", err)
}
defer dagentryRows.Close()
for dagentryRows.Next() {
var entryKey [2]string
var ourLastUpd time.Time
if err = dagentryRows.Scan(&entryKey[0], &entryKey[1], &ourLastUpd); err != nil {
return err
}
existingDags++
if r, found := remoteDags[entryKey]; found && !ourLastUpd.Before(r.UpdatedAt) {
delete(remoteDags, entryKey)
}
}
if err = dagentryRows.Err(); err != nil {
return xerrors.Errorf("Pg error: %w", err)
}
dagentryRows.Close()
log.Infof("%s: iterated through %d already-existing dag entries", projPrefix, existingDags)
// now deal with sources
// since we pull them after we pulled the dags, we will see each source by definition
seenSrcLabels := make(map[string]struct{}, len(remoteDags))
toGetSrcLabels := make([]string, 0, len(remoteDags))
for _, d := range remoteDags {
if _, seen := seenSrcLabels[d.sourceLabel]; !seen {
seenSrcLabels[d.sourceLabel] = struct{}{}
toGetSrcLabels = append(toGetSrcLabels, d.sourceLabel)
}
}
srcRows, err := srcDb.Query(
ctx,
fmt.Sprintf(
`
SELECT
s.id::TEXT AS source_label,
s.inserted_at AS entry_created,
%s AS details,
( s.email LIKE 'niftysave%%@nft.storage' ) AS is_niftysave
FROM public.user s
WHERE
s.updated_at > $1
OR
s.id::TEXT = ANY( $2 )
`,
p.templatedSQLDetailsUser,
),
cutoff,
toGetSrcLabels,
)
if err != nil {
return xerrors.Errorf("Pg error: %w", err)
}
defer srcRows.Close()
srcMap := make(map[string]*int64)
for srcRows.Next() {
var isNewSource, isNifty bool
var s dagSource
if err = srcRows.Scan(&s.SourceLabel, &s.CreatedAt, &s.Details, &isNifty); err != nil {
return err
}
if isNifty {
log.Infof("Skipping niftysave source %s", s.SourceLabel)
continue
}
err = cargoDb.QueryRow(
ctx,
`
INSERT INTO cargo.sources ( project, source_label, entry_created, details ) VALUES ( $1, $2, $3, $4 )
ON CONFLICT ( project, source_label ) DO UPDATE SET
entry_created = LEAST( cargo.sources.entry_created, EXCLUDED.entry_created ),
details = EXCLUDED.details
RETURNING srcid, (xmax = 0)
`,
p.id,
s.SourceLabel,
s.CreatedAt,
s.Details,
).Scan(&s.SourceID, &isNewSource)
if err != nil {
return xerrors.Errorf("Pg error: %w", err)
}
if isNewSource {
newSources++
}
srcMap[s.SourceLabel] = &s.SourceID
}
if err = srcRows.Err(); err != nil {
return xerrors.Errorf("Pg error: %w", err)
}
srcRows.Close()
log.Infof("%s: upserted %d sources (users)", projPrefix, len(srcMap))
// and insert everything
// FIXME - iterating like this is pretty slow: need to switch to temptable COPY + INSERT SELECT
for _, d := range remoteDags {
d.SourceID = srcMap[d.sourceLabel]
if d.cidV1.Prefix().Codec == 0 {
// log.Warnw("ignore record with invalid cid", "struct", d)
continue
}
if _, known := knownDags[d.cidV1]; !known {
_, err = cargoDb.Exec(
ctx,
`
INSERT INTO cargo.dags ( cid_v1, entry_created ) VALUES ( $1, $2 )
ON CONFLICT DO NOTHING
`,
d.CidV1Str,
d.CreatedAt,
)
if err != nil {
return xerrors.Errorf("Pg error: %w", err)
}
}
if d.SourceID == nil {
// log.Infof("skipping sourceless entry %s from skipped %s", d.SourceKey, d.sourceLabel)
continue
}
var isNew, wasAlreadyRemoved bool
err = cargoDb.QueryRow(
ctx,
`
INSERT INTO cargo.dag_sources ( cid_v1, source_key, srcid, size_claimed, entry_created, entry_removed, entry_last_updated, details )
VALUES ( $1, $2, $3, $4, $5, $6, $7, $8 )
ON CONFLICT ( srcid, source_key ) DO UPDATE SET
size_claimed = EXCLUDED.size_claimed,
details = EXCLUDED.details,
entry_created = LEAST( cargo.dag_sources.entry_created, EXCLUDED.entry_created ),
entry_removed = EXCLUDED.entry_removed,
entry_last_updated = EXCLUDED.entry_last_updated
RETURNING
(xmax = 0),
-- this select sees the table as it was before the upsert
-- the COALESCE is needed in case of INSERTs - we won't find anything prior
COALESCE (
(
SELECT resel.entry_removed IS NOT NULL
FROM cargo.dag_sources resel
WHERE
resel.srcid = dag_sources.srcid
AND
resel.source_key = dag_sources.source_key
),
false
)
`,
d.CidV1Str,
d.SourceKey,
d.SourceID,
d.SizeClaimed,
d.CreatedAt,
d.RemovedAt,
d.UpdatedAt,
d.Details,
).Scan(&isNew, &wasAlreadyRemoved)
if err != nil {
return xerrors.Errorf("Pg error: %w", err)
}
if d.RemovedAt != nil && !wasAlreadyRemoved {
removedDags++
} else if isNew {
newDags++
}
}
return nil
}