@open-workspace/create 0.4.2 → 0.5.1
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/README.md +9 -5
- package/dist/backup-schema.ts +110 -0
- package/dist/workspace.ts +162 -0
- package/import/backup-snapshot.ts +254 -0
- package/import/backup-source.ts +270 -0
- package/import/cli.ts +134 -90
- package/import/concurrency.ts +34 -37
- package/import/csv.ts +1 -1
- package/import/directory/command.ts +302 -72
- package/import/directory/google.ts +159 -121
- package/import/directory/invitation-file.ts +108 -0
- package/import/directory/plan.ts +314 -38
- package/import/directory/read.ts +55 -0
- package/import/gmail.ts +9 -12
- package/import/headers.ts +1 -1
- package/import/idp/apps.ts +244 -0
- package/import/idp/command.ts +167 -0
- package/import/idp/csv.ts +70 -0
- package/import/idp/entra.ts +297 -0
- package/import/idp/keycloak.ts +250 -0
- package/import/idp/model.ts +108 -0
- package/import/idp/okta.ts +161 -0
- package/import/idp/pages.ts +65 -0
- package/import/imap-command.ts +42 -18
- package/import/imap-source.ts +245 -220
- package/import/invariant.ts +1 -1
- package/import/loopback.ts +136 -0
- package/import/mbox-source.ts +106 -55
- package/import/mbox.ts +8 -8
- package/import/oauth.ts +234 -138
- package/import/preview.ts +48 -0
- package/import/uploader.ts +169 -115
- package/import/workspace.ts +78 -15
- package/index.ts +3 -0
- package/module-templates.ts +9 -12
- package/module.ts +1 -5
- package/package.json +13 -2
- package/setup/alchemy.ts +2 -2
- package/setup/args.ts +16 -17
- package/setup/cloudflare-api.ts +75 -19
- package/setup/domains.ts +18 -6
- package/setup/flow.ts +217 -58
- package/setup/migration-guide.ts +255 -0
- package/setup/mx-recovery.ts +115 -0
- package/setup/ui.ts +4 -1
- package/templates.ts +26 -18
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { basename, dirname, join } from "node:path";
|
|
3
|
+
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
|
|
6
|
+
import { coreBackupSchema } from "#backup-schema";
|
|
7
|
+
|
|
8
|
+
import { parseCliArgs } from "./args.ts";
|
|
9
|
+
import {
|
|
10
|
+
backupItems,
|
|
11
|
+
inspectSnapshot,
|
|
12
|
+
readBackupObject,
|
|
13
|
+
restoreBody,
|
|
14
|
+
sha256,
|
|
15
|
+
} from "./backup-snapshot.ts";
|
|
16
|
+
import type { BackupLine } from "./backup-snapshot.ts";
|
|
17
|
+
import {
|
|
18
|
+
commonOptions,
|
|
19
|
+
concurrency,
|
|
20
|
+
connect,
|
|
21
|
+
reportedRun,
|
|
22
|
+
UsageError,
|
|
23
|
+
} from "./cli.ts";
|
|
24
|
+
import type { CliDeps } from "./cli.ts";
|
|
25
|
+
import { ResumeState, runResumable } from "./uploader.ts";
|
|
26
|
+
import type { Workspace } from "./workspace.ts";
|
|
27
|
+
|
|
28
|
+
export { backupItems } from "./backup-snapshot.ts";
|
|
29
|
+
|
|
30
|
+
export type { BackupItem } from "./backup-snapshot.ts";
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* `import backup`: a snapshot of the workspace's scheduled backups,
|
|
34
|
+
* copied out of the bucket (`backups/<id>/` next to `backups/objects/`).
|
|
35
|
+
* core.json goes back first (people, teams, addresses, SSO apps, webhooks,
|
|
36
|
+
* branding), then each module's lines, each with the object it names
|
|
37
|
+
* (`@open-workspace/core`, worker/backups/). What exists is left alone.
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* What a full restore needs, from an administrator: the workspace restores
|
|
42
|
+
* each part only as far as the token reaches, as its admin API would
|
|
43
|
+
* (people and their addresses, teams and theirs, webhooks, single sign-on
|
|
44
|
+
* apps; roles and apps also need admin.access), and mail as far as its
|
|
45
|
+
* own routes would let it be written (messages and settings into any
|
|
46
|
+
* mailbox with admin.import_mail, settings with mail.organize, drafts with
|
|
47
|
+
* mail.send, the workspace's blocked senders with admin.blocked_senders).
|
|
48
|
+
*/
|
|
49
|
+
const CORE_BACKUP_SCOPES = [
|
|
50
|
+
"admin.workspace",
|
|
51
|
+
"admin.people",
|
|
52
|
+
"admin.teams",
|
|
53
|
+
"admin.webhooks",
|
|
54
|
+
"admin.apps",
|
|
55
|
+
"admin.access",
|
|
56
|
+
"offline_access",
|
|
57
|
+
];
|
|
58
|
+
|
|
59
|
+
const EMAIL_BACKUP_SCOPES = [
|
|
60
|
+
"admin.import_mail",
|
|
61
|
+
"admin.blocked_senders",
|
|
62
|
+
"mail.organize",
|
|
63
|
+
"mail.send",
|
|
64
|
+
];
|
|
65
|
+
|
|
66
|
+
export const BACKUP_SCOPES = [...CORE_BACKUP_SCOPES, ...EMAIL_BACKUP_SCOPES];
|
|
67
|
+
|
|
68
|
+
const restoreAnswer = z.discriminatedUnion("status", [
|
|
69
|
+
z.object({ status: z.enum(["restored", "exists"]) }),
|
|
70
|
+
z.object({ status: z.literal("skipped"), reason: z.string() }),
|
|
71
|
+
]);
|
|
72
|
+
|
|
73
|
+
/** Sends one line to its module, as `runResumable` sends each. */
|
|
74
|
+
async function restoreLine(workspace: Workspace, line: BackupLine) {
|
|
75
|
+
const path = `/api/admin/backups/restore/${encodeURIComponent(line.module)}?folder=${encodeURIComponent(line.folder)}`;
|
|
76
|
+
|
|
77
|
+
for (const part of line.parts) {
|
|
78
|
+
const name = basename(part);
|
|
79
|
+
const data = readBackupObject(dirname(part), name);
|
|
80
|
+
|
|
81
|
+
if (!data.bytes) return { skipped: data.problem ?? "damaged" };
|
|
82
|
+
|
|
83
|
+
// oxlint-disable-next-line eslint/no-await-in-loop -- one file part in memory per concurrent restore
|
|
84
|
+
const answer = await workspace.json(path, restoreAnswer, {
|
|
85
|
+
method: "POST",
|
|
86
|
+
raw: restoreBody(
|
|
87
|
+
JSON.stringify({ kind: "backup-part", object: name }),
|
|
88
|
+
data.bytes
|
|
89
|
+
),
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
if (answer.status === "skipped") {
|
|
93
|
+
return { skipped: answer.reason };
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const answer = await workspace.json(path, restoreAnswer, {
|
|
98
|
+
method: "POST",
|
|
99
|
+
raw: line.body,
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
// A line the workspace skipped (its address is missing, say) is not
|
|
103
|
+
// done: it is sent again once that changes.
|
|
104
|
+
return answer.status === "skipped"
|
|
105
|
+
? { skipped: answer.reason }
|
|
106
|
+
: { done: answer.status };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const coreAnswer = z.object({
|
|
110
|
+
restored: z.record(z.string(), z.union([z.number(), z.boolean()])),
|
|
111
|
+
/** What the workspace left out, and why. */
|
|
112
|
+
skipped: z.array(z.string()),
|
|
113
|
+
clientsNeedingSecret: z.array(z.string()),
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
export async function backupCommand(args: string[], deps: CliDeps) {
|
|
117
|
+
const { values, positionals } = parseCliArgs({
|
|
118
|
+
args,
|
|
119
|
+
allowPositionals: true,
|
|
120
|
+
options: { ...commonOptions, partial: { type: "boolean" } },
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
if (values.help) {
|
|
124
|
+
console.log(`bunx @open-workspace/create import backup <backups/<id>>
|
|
125
|
+
|
|
126
|
+
Restores a snapshot of the workspace's backups: people (invited again),
|
|
127
|
+
teams, addresses, SSO apps, webhooks and branding that are missing, then
|
|
128
|
+
each module's data, such as mail each address is missing.
|
|
129
|
+
--partial restore available data from an incomplete or damaged snapshot
|
|
130
|
+
--concurrency, --state-dir, --dry-run as for mbox`);
|
|
131
|
+
|
|
132
|
+
return 0;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const [snapshot] = positionals;
|
|
136
|
+
|
|
137
|
+
if (!snapshot || !existsSync(join(snapshot, "core.json"))) {
|
|
138
|
+
throw new UsageError("Name a snapshot folder, the one with core.json");
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const raw: unknown = JSON.parse(
|
|
142
|
+
readFileSync(join(snapshot, "core.json"), "utf-8")
|
|
143
|
+
);
|
|
144
|
+
|
|
145
|
+
const core = coreBackupSchema.safeParse(raw);
|
|
146
|
+
|
|
147
|
+
if (!core.success) {
|
|
148
|
+
if (core.error.issues.some((issue) => issue.path[0] === "version")) {
|
|
149
|
+
throw new UsageError(
|
|
150
|
+
"Unsupported snapshot format. Restore this snapshot with its matching OpenWorkspace release."
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
throw new UsageError(`Invalid core.json: ${z.prettifyError(core.error)}`);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// complete.json is written last: without it the snapshot was still being
|
|
158
|
+
// written (or failed) when it was copied, and may lack part of the data.
|
|
159
|
+
const manifestPath = join(snapshot, "complete.json");
|
|
160
|
+
|
|
161
|
+
const manifest = existsSync(manifestPath)
|
|
162
|
+
? z
|
|
163
|
+
.object({
|
|
164
|
+
id: z.string().min(1),
|
|
165
|
+
items: z.number().int().nonnegative(),
|
|
166
|
+
errors: z.array(z.string()),
|
|
167
|
+
})
|
|
168
|
+
.parse(JSON.parse(readFileSync(manifestPath, "utf-8")))
|
|
169
|
+
: null;
|
|
170
|
+
|
|
171
|
+
const log = deps.log ?? ((message: string) => console.error(message));
|
|
172
|
+
|
|
173
|
+
const problem = manifest
|
|
174
|
+
? manifest.errors.length > 0
|
|
175
|
+
? `This snapshot recorded ${manifest.errors.length} backup error(s)`
|
|
176
|
+
: null
|
|
177
|
+
: "This snapshot is incomplete (no complete.json)";
|
|
178
|
+
|
|
179
|
+
if (problem) {
|
|
180
|
+
for (const reason of manifest?.errors ?? []) log(reason);
|
|
181
|
+
|
|
182
|
+
if (!values.partial) {
|
|
183
|
+
throw new UsageError(
|
|
184
|
+
`${problem}: pick an earlier snapshot, or pass --partial to restore what it has`
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
log(`${problem}. Restoring available data only.`);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const inspection = inspectSnapshot(snapshot, manifest?.items, log);
|
|
192
|
+
|
|
193
|
+
if (values["dry-run"]) {
|
|
194
|
+
for (const [key, count] of inspection.counts) log(`${key}: ${count} lines`);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
if (inspection.incomplete && !values.partial) {
|
|
198
|
+
throw new UsageError(
|
|
199
|
+
"Copy the missing or damaged records again, or use --partial to restore available records."
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
if (values["dry-run"]) return inspection.incomplete ? 1 : 0;
|
|
204
|
+
|
|
205
|
+
const snapshotKey = manifest?.id ?? `partial:${snapshot}`;
|
|
206
|
+
|
|
207
|
+
const workspace = await connect(
|
|
208
|
+
values,
|
|
209
|
+
CORE_BACKUP_SCOPES,
|
|
210
|
+
deps,
|
|
211
|
+
EMAIL_BACKUP_SCOPES
|
|
212
|
+
);
|
|
213
|
+
|
|
214
|
+
const { restored, skipped, clientsNeedingSecret } = await workspace.json(
|
|
215
|
+
"/api/admin/backups/restore",
|
|
216
|
+
coreAnswer,
|
|
217
|
+
{
|
|
218
|
+
method: "POST",
|
|
219
|
+
body: core.data,
|
|
220
|
+
}
|
|
221
|
+
);
|
|
222
|
+
|
|
223
|
+
log(
|
|
224
|
+
`Workspace: ${Object.entries(restored)
|
|
225
|
+
.map(([kind, count]) => `${kind} ${String(count)}`)
|
|
226
|
+
.join(", ")} restored (people are invited again)`
|
|
227
|
+
);
|
|
228
|
+
|
|
229
|
+
for (const reason of skipped) log(`Workspace: skipped ${reason}`);
|
|
230
|
+
|
|
231
|
+
for (const name of clientsNeedingSecret) {
|
|
232
|
+
log(
|
|
233
|
+
`OIDC app "${name}" is disabled. Rotate its client secret and configure it in the app before enabling sign-in.`
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const state = new ResumeState(
|
|
238
|
+
values["state-dir"] ?? ".openworkspace-import",
|
|
239
|
+
`restore-in-progress-${sha256(JSON.stringify([workspace.origin, snapshotKey]))}`
|
|
240
|
+
);
|
|
241
|
+
|
|
242
|
+
const stats = await reportedRun({
|
|
243
|
+
deps,
|
|
244
|
+
label: "Lines",
|
|
245
|
+
outcomes: { restored: "restored", exists: "already there" },
|
|
246
|
+
state,
|
|
247
|
+
run: (onProgress) =>
|
|
248
|
+
runResumable<BackupLine>({
|
|
249
|
+
// Each part is checked again on the bytes actually sent by restoreLine.
|
|
250
|
+
items: backupItems(snapshot, values.partial ? null : undefined, false),
|
|
251
|
+
state,
|
|
252
|
+
concurrency: concurrency(values),
|
|
253
|
+
exclusive: (line) => !("skipped" in line) && line.ordered,
|
|
254
|
+
size: (line) => line.bytes,
|
|
255
|
+
send: (line) => restoreLine(workspace, line),
|
|
256
|
+
onProgress,
|
|
257
|
+
}),
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
const incomplete =
|
|
261
|
+
inspection.incomplete ||
|
|
262
|
+
skipped.length > 0 ||
|
|
263
|
+
stats.failed > 0 ||
|
|
264
|
+
stats.skipped.size > 0;
|
|
265
|
+
|
|
266
|
+
// A later restore of the same snapshot must check what the workspace still has.
|
|
267
|
+
if (!incomplete) state.clearProgress();
|
|
268
|
+
|
|
269
|
+
return incomplete ? 1 : 0;
|
|
270
|
+
}
|
package/import/cli.ts
CHANGED
|
@@ -7,20 +7,33 @@ import { mboxFiles, mboxItems, scanMbox } from "./mbox-source.ts";
|
|
|
7
7
|
import type { MboxSourceOptions } from "./mbox-source.ts";
|
|
8
8
|
import { OAuthSession, StaticToken } from "./oauth.ts";
|
|
9
9
|
import type { Fetch, TokenSource } from "./oauth.ts";
|
|
10
|
+
import { ImportPreview } from "./preview.ts";
|
|
10
11
|
import { MAIL_IMPORT_SCOPES, placementSchema } from "./protocol.ts";
|
|
11
|
-
import type {
|
|
12
|
-
|
|
13
|
-
|
|
12
|
+
import type {
|
|
13
|
+
ImportItem,
|
|
14
|
+
ImportTarget,
|
|
15
|
+
Placement,
|
|
16
|
+
SkippedItem,
|
|
17
|
+
} from "./protocol.ts";
|
|
18
|
+
import {
|
|
19
|
+
progressLine,
|
|
20
|
+
ResumeState,
|
|
21
|
+
upload,
|
|
22
|
+
UPLOAD_OUTCOMES,
|
|
23
|
+
} from "./uploader.ts";
|
|
24
|
+
import type { RunStats } from "./uploader.ts";
|
|
14
25
|
import { Workspace } from "./workspace.ts";
|
|
15
26
|
|
|
16
|
-
const USAGE = `Bring people and mail into an OpenWorkspace.
|
|
27
|
+
const USAGE = `Bring people, teams, SSO apps and mail into an OpenWorkspace.
|
|
17
28
|
|
|
18
|
-
bunx @open-workspace/create import mbox <file or
|
|
29
|
+
bunx @open-workspace/create import mbox <mbox file, Apple Mail package or export folder>... --into <mailbox>
|
|
19
30
|
bunx @open-workspace/create import imap --host <host> --user <user> --into <mailbox>
|
|
20
31
|
bunx @open-workspace/create import people --google-credentials <file.json> [--admin <email>]
|
|
32
|
+
bunx @open-workspace/create import idp <entra|okta|keycloak|csv|saml> --help
|
|
33
|
+
bunx @open-workspace/create import backup <backups/<id> folder>
|
|
21
34
|
|
|
22
35
|
Common options:
|
|
23
|
-
--workspace <url> The workspace, e.g. https://
|
|
36
|
+
--workspace <url> The workspace, e.g. https://workspace.acme.com (or OPENWORKSPACE_URL)
|
|
24
37
|
--into <mailbox> Target mailbox: its address or id
|
|
25
38
|
--map <file.csv> Many sources at once: rows of "source,target" (imap: "user,target[,password]")
|
|
26
39
|
--concurrency <n> Uploads in flight per mailbox (default 2)
|
|
@@ -76,7 +89,7 @@ export type CommonValues = {
|
|
|
76
89
|
|
|
77
90
|
export class UsageError extends Error {}
|
|
78
91
|
|
|
79
|
-
function required<T>(value: T | undefined, message: string)
|
|
92
|
+
function required<T>(value: T | undefined, message: string) {
|
|
80
93
|
if (value === undefined || value === "") throw new UsageError(message);
|
|
81
94
|
|
|
82
95
|
return value;
|
|
@@ -86,7 +99,8 @@ function required<T>(value: T | undefined, message: string): T {
|
|
|
86
99
|
export async function connect(
|
|
87
100
|
values: CommonValues,
|
|
88
101
|
scopes: string[],
|
|
89
|
-
deps: CliDeps
|
|
102
|
+
deps: CliDeps,
|
|
103
|
+
optionalScopes?: string[]
|
|
90
104
|
) {
|
|
91
105
|
const url = required(
|
|
92
106
|
values.workspace ?? process.env.OPENWORKSPACE_URL,
|
|
@@ -100,6 +114,7 @@ export async function connect(
|
|
|
100
114
|
: await OAuthSession.login({
|
|
101
115
|
workspace: url,
|
|
102
116
|
scopes,
|
|
117
|
+
optionalScopes,
|
|
103
118
|
fetch: deps.fetch,
|
|
104
119
|
openBrowser: deps.openBrowser,
|
|
105
120
|
credentialsPath: deps.credentialsPath,
|
|
@@ -114,11 +129,11 @@ export async function connect(
|
|
|
114
129
|
export type Job = { source: string; target: string; password?: string };
|
|
115
130
|
|
|
116
131
|
/** Source → target pairs from --map, or the one source with --into. */
|
|
117
|
-
export function jobs(values: CommonValues, sources: string[])
|
|
132
|
+
export function jobs(values: CommonValues, sources: string[]) {
|
|
118
133
|
if (values.map) {
|
|
119
134
|
const rows = parseCsv(readFileSync(values.map, "utf-8"));
|
|
120
135
|
|
|
121
|
-
return rows.flatMap((row, index)
|
|
136
|
+
return rows.flatMap((row, index) => {
|
|
122
137
|
const [source = "", target = "", password] = row;
|
|
123
138
|
|
|
124
139
|
// A header row ("source,target") is allowed.
|
|
@@ -164,95 +179,102 @@ function progressPrinter(deps: CliDeps) {
|
|
|
164
179
|
};
|
|
165
180
|
}
|
|
166
181
|
|
|
167
|
-
/**
|
|
168
|
-
export
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
182
|
+
/** Requests in flight: --concurrency, 2 by default. */
|
|
183
|
+
export function concurrency(values: CommonValues) {
|
|
184
|
+
return Math.max(1, Number(values.concurrency ?? 2) || 2);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Runs a resumable run (`runResumable`) with a progress line, then reports
|
|
189
|
+
* what it did, each reason for skipping, and where its failures are.
|
|
190
|
+
*/
|
|
191
|
+
export async function reportedRun(input: {
|
|
176
192
|
deps: CliDeps;
|
|
193
|
+
label: string;
|
|
194
|
+
outcomes: Record<string, string>;
|
|
195
|
+
state: ResumeState;
|
|
196
|
+
run: (onProgress: (stats: RunStats) => void) => Promise<RunStats>;
|
|
177
197
|
}) {
|
|
178
198
|
const log = input.deps.log ?? ((message: string) => console.error(message));
|
|
179
|
-
const mailbox = await input.workspace.importTarget(input.target);
|
|
180
|
-
|
|
181
|
-
const state = new ResumeState(
|
|
182
|
-
input.values["state-dir"] ?? ".openworkspace-import",
|
|
183
|
-
`${new URL(input.workspace.origin).host}-${mailbox.id}-${input.job}`
|
|
184
|
-
);
|
|
185
|
-
|
|
186
199
|
const print = progressPrinter(input.deps);
|
|
187
|
-
const label = `${input.label} → ${mailbox.address}`;
|
|
188
200
|
|
|
189
|
-
const stats
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
items: input.items,
|
|
193
|
-
state,
|
|
194
|
-
concurrency: Math.max(1, Number(input.values.concurrency ?? 2) || 2),
|
|
195
|
-
total: input.total,
|
|
196
|
-
onProgress: (current) => print(progressLine(label, current)),
|
|
197
|
-
});
|
|
201
|
+
const stats = await input.run((current) =>
|
|
202
|
+
print(progressLine(input.label, current, input.outcomes))
|
|
203
|
+
);
|
|
198
204
|
|
|
199
205
|
if (process.stderr.isTTY && !input.deps.progress) process.stderr.write("\n");
|
|
200
|
-
log(progressLine(label, stats));
|
|
206
|
+
log(progressLine(input.label, stats, input.outcomes));
|
|
201
207
|
|
|
202
|
-
|
|
203
|
-
log(
|
|
204
|
-
` ${stats.failed} failed; see ${state.failuresPath}. Run the same command again to retry them.`
|
|
205
|
-
);
|
|
208
|
+
for (const [reason, count] of stats.skipped) {
|
|
209
|
+
log(` skipped (${reason}): ${count}`);
|
|
206
210
|
}
|
|
207
211
|
|
|
208
|
-
if (stats.
|
|
212
|
+
if (stats.failed) {
|
|
209
213
|
log(
|
|
210
|
-
` ${stats.
|
|
214
|
+
` ${stats.failed} failed; see ${input.state.failuresPath}. Run the same command again to retry them.`
|
|
211
215
|
);
|
|
212
216
|
}
|
|
213
217
|
|
|
214
218
|
return stats;
|
|
215
219
|
}
|
|
216
220
|
|
|
217
|
-
/**
|
|
218
|
-
export async function
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
221
|
+
/** The source reader and uploader share the same mailbox and resume state. */
|
|
222
|
+
export async function prepareImportJob(
|
|
223
|
+
workspace: Workspace,
|
|
224
|
+
target: string,
|
|
225
|
+
job: string,
|
|
226
|
+
directory = ".openworkspace-import"
|
|
222
227
|
) {
|
|
223
|
-
const
|
|
224
|
-
const folders = new Map<string, number>();
|
|
225
|
-
const skipped = new Map<string, number>();
|
|
226
|
-
let unread = 0;
|
|
227
|
-
let count = 0;
|
|
228
|
-
|
|
229
|
-
for await (const item of items) {
|
|
230
|
-
count += 1;
|
|
231
|
-
|
|
232
|
-
if ("skipped" in item) {
|
|
233
|
-
skipped.set(item.skipped, (skipped.get(item.skipped) ?? 0) + 1);
|
|
234
|
-
continue;
|
|
235
|
-
}
|
|
228
|
+
const mailbox = await workspace.importTarget(target);
|
|
236
229
|
|
|
237
|
-
|
|
230
|
+
const state = new ResumeState(
|
|
231
|
+
directory,
|
|
232
|
+
`${new URL(workspace.origin).host}-${mailbox.id}-${job}`
|
|
233
|
+
);
|
|
238
234
|
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
}
|
|
235
|
+
return { workspace, mailbox, state };
|
|
236
|
+
}
|
|
242
237
|
|
|
243
|
-
|
|
244
|
-
|
|
238
|
+
/** Uploads one source's items into one mailbox and reports the outcome. */
|
|
239
|
+
export async function runJob(input: {
|
|
240
|
+
workspace: Workspace;
|
|
241
|
+
mailbox: ImportTarget;
|
|
242
|
+
state: ResumeState;
|
|
243
|
+
label: string;
|
|
244
|
+
items: AsyncIterable<ImportItem | SkippedItem>;
|
|
245
|
+
total: number | null;
|
|
246
|
+
values: CommonValues;
|
|
247
|
+
deps: CliDeps;
|
|
248
|
+
}) {
|
|
249
|
+
const log = input.deps.log ?? ((message: string) => console.error(message));
|
|
250
|
+
const { mailbox, state } = input;
|
|
245
251
|
|
|
246
|
-
const
|
|
247
|
-
|
|
252
|
+
const stats = await reportedRun({
|
|
253
|
+
deps: input.deps,
|
|
254
|
+
label: `${input.label} → ${mailbox.address}`,
|
|
255
|
+
outcomes: UPLOAD_OUTCOMES,
|
|
256
|
+
state,
|
|
257
|
+
run: (onProgress) =>
|
|
258
|
+
upload({
|
|
259
|
+
workspace: input.workspace,
|
|
260
|
+
mailboxId: mailbox.id,
|
|
261
|
+
items: input.items,
|
|
262
|
+
state,
|
|
263
|
+
concurrency: concurrency(input.values),
|
|
264
|
+
total: input.total,
|
|
265
|
+
onProgress,
|
|
266
|
+
}),
|
|
267
|
+
});
|
|
248
268
|
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
269
|
+
const withoutFolder = stats.done.importedWithoutFolder;
|
|
270
|
+
|
|
271
|
+
if (withoutFolder) {
|
|
272
|
+
log(
|
|
273
|
+
` ${withoutFolder} messages kept no folder (a mailbox has at most 100, and system folder names are taken).`
|
|
274
|
+
);
|
|
275
|
+
}
|
|
254
276
|
|
|
255
|
-
return
|
|
277
|
+
return stats;
|
|
256
278
|
}
|
|
257
279
|
|
|
258
280
|
/** --skip: comma-separated places. */
|
|
@@ -320,22 +342,32 @@ export async function mboxCommand(args: string[], deps: CliDeps) {
|
|
|
320
342
|
};
|
|
321
343
|
|
|
322
344
|
const log = deps.log ?? ((message: string) => console.error(message));
|
|
323
|
-
|
|
345
|
+
|
|
346
|
+
const pairs = jobs(values, positionals).map(({ source, target }) => {
|
|
347
|
+
const files = mboxFiles(source.split("\u0000"));
|
|
348
|
+
|
|
349
|
+
if (!files.length) throw new UsageError(`No mbox files in ${source}`);
|
|
350
|
+
const archive = files.find((file) => /\.(?:zip|tgz|gz)$/iu.test(file));
|
|
351
|
+
|
|
352
|
+
if (archive) {
|
|
353
|
+
throw new UsageError(
|
|
354
|
+
`Extract ${archive} first, then pass the .mbox file or the extracted Takeout/Mail folder.`
|
|
355
|
+
);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
return { files, target };
|
|
359
|
+
});
|
|
324
360
|
|
|
325
361
|
const workspace = values["dry-run"]
|
|
326
362
|
? null
|
|
327
363
|
: await connect(values, MAIL_IMPORT_SCOPES, deps);
|
|
328
364
|
|
|
329
|
-
const results:
|
|
365
|
+
const results: RunStats[] = [];
|
|
330
366
|
|
|
331
|
-
const mboxJob = async ({
|
|
332
|
-
const files = mboxFiles(source.split("\u0000"));
|
|
333
|
-
|
|
334
|
-
if (!files.length) throw new UsageError(`No mbox files in ${source}`);
|
|
367
|
+
const mboxJob = async ({ files, target }: (typeof pairs)[number]) => {
|
|
335
368
|
log(
|
|
336
369
|
`Reading ${files.length === 1 ? files[0] : `${files.length} mbox files`}…`
|
|
337
370
|
);
|
|
338
|
-
const scan = await scanMbox(files, options);
|
|
339
371
|
const [only] = files;
|
|
340
372
|
|
|
341
373
|
const label =
|
|
@@ -344,21 +376,28 @@ export async function mboxCommand(args: string[], deps: CliDeps) {
|
|
|
344
376
|
: `${files.length} mbox files`;
|
|
345
377
|
|
|
346
378
|
if (!workspace) {
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
`${label} → ${target}`
|
|
351
|
-
);
|
|
379
|
+
const preview = new ImportPreview();
|
|
380
|
+
await scanMbox(files, options, preview);
|
|
381
|
+
preview.print(log, `${label} → ${target}`);
|
|
352
382
|
|
|
353
383
|
return;
|
|
354
384
|
}
|
|
355
385
|
|
|
386
|
+
const scan = await scanMbox(files, options);
|
|
387
|
+
|
|
388
|
+
const job = `mbox-${new Bun.CryptoHasher("sha256").update(files.join("\n")).digest("hex").slice(0, 12)}`;
|
|
389
|
+
|
|
390
|
+
const destination = await prepareImportJob(
|
|
391
|
+
workspace,
|
|
392
|
+
target,
|
|
393
|
+
job,
|
|
394
|
+
values["state-dir"]
|
|
395
|
+
);
|
|
396
|
+
|
|
356
397
|
results.push(
|
|
357
398
|
await runJob({
|
|
358
|
-
|
|
359
|
-
target,
|
|
399
|
+
...destination,
|
|
360
400
|
label,
|
|
361
|
-
job: `mbox-${new Bun.CryptoHasher("sha256").update(files.join("\n")).digest("hex").slice(0, 12)}`,
|
|
362
401
|
items: mboxItems(files, options, scan.threads),
|
|
363
402
|
total: scan.count,
|
|
364
403
|
values,
|
|
@@ -379,12 +418,17 @@ type Command = (args: string[], deps: CliDeps) => Promise<number>;
|
|
|
379
418
|
|
|
380
419
|
/** Each source's command; the IMAP and directory ones load their dependencies only when used. */
|
|
381
420
|
const commands = new Map<string, () => Promise<Command>>([
|
|
421
|
+
["idp", () => import("./idp/command.ts").then((module) => module.idpCommand)],
|
|
382
422
|
["mbox", () => Promise.resolve(mboxCommand)],
|
|
383
423
|
["takeout", () => Promise.resolve(mboxCommand)],
|
|
384
424
|
[
|
|
385
425
|
"imap",
|
|
386
426
|
() => import("./imap-command.ts").then((module) => module.imapCommand),
|
|
387
427
|
],
|
|
428
|
+
[
|
|
429
|
+
"backup",
|
|
430
|
+
() => import("./backup-source.ts").then((module) => module.backupCommand),
|
|
431
|
+
],
|
|
388
432
|
[
|
|
389
433
|
"people",
|
|
390
434
|
() =>
|
package/import/concurrency.ts
CHANGED
|
@@ -7,46 +7,43 @@
|
|
|
7
7
|
export async function forEachConcurrent<Item>(
|
|
8
8
|
items: AsyncIterable<Item> | Iterable<Item>,
|
|
9
9
|
limit: number,
|
|
10
|
-
task: (item: Item, index: number) => Promise<void
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
let stopped = false;
|
|
19
|
-
const failures: Promise<void>[] = [];
|
|
20
|
-
|
|
21
|
-
const work = async () => {
|
|
22
|
-
/* oxlint-disable eslint/no-await-in-loop -- a worker takes its next item only when its last task is done: that is the concurrency bound */
|
|
23
|
-
for (;;) {
|
|
24
|
-
// Set by another worker's failure while this one waited.
|
|
25
|
-
if (stopped) return;
|
|
26
|
-
const next = await source.next();
|
|
27
|
-
|
|
28
|
-
if (next.done) return;
|
|
29
|
-
const index = taken;
|
|
30
|
-
taken += 1;
|
|
31
|
-
await task(next.value, index);
|
|
32
|
-
}
|
|
33
|
-
/* oxlint-enable eslint/no-await-in-loop */
|
|
10
|
+
task: (item: Item, index: number) => Promise<void>,
|
|
11
|
+
exclusive?: (item: Item) => boolean
|
|
12
|
+
) {
|
|
13
|
+
const active = new Set<Promise<void>>();
|
|
14
|
+
let failure: { cause: unknown } | undefined;
|
|
15
|
+
|
|
16
|
+
const rememberFailure = (cause: unknown) => {
|
|
17
|
+
failure ??= { cause };
|
|
34
18
|
};
|
|
35
19
|
|
|
36
|
-
|
|
37
|
-
const running = work();
|
|
20
|
+
let index = 0;
|
|
38
21
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
};
|
|
22
|
+
try {
|
|
23
|
+
for await (const item of items) {
|
|
24
|
+
// An ordered restore line needs the preceding messages and draft owners.
|
|
25
|
+
const alone = exclusive?.(item);
|
|
26
|
+
|
|
27
|
+
if (alone) await Promise.all(active);
|
|
46
28
|
|
|
47
|
-
|
|
48
|
-
|
|
29
|
+
if (failure) break;
|
|
30
|
+
|
|
31
|
+
const running = task(item, index++)
|
|
32
|
+
.catch(rememberFailure)
|
|
33
|
+
.finally(() => {
|
|
34
|
+
active.delete(running);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
active.add(running);
|
|
38
|
+
|
|
39
|
+
if (alone) await running;
|
|
40
|
+
else if (active.size >= Math.max(1, limit)) await Promise.race(active);
|
|
41
|
+
|
|
42
|
+
if (failure) break;
|
|
43
|
+
}
|
|
44
|
+
} finally {
|
|
45
|
+
await Promise.all(active);
|
|
46
|
+
}
|
|
49
47
|
|
|
50
|
-
|
|
51
|
-
if (failures.length > 0) await failures[0];
|
|
48
|
+
if (failure) throw failure.cause;
|
|
52
49
|
}
|