-
Notifications
You must be signed in to change notification settings - Fork 179
Expand file tree
/
Copy pathplanner.ts
More file actions
1347 lines (1256 loc) · 49.8 KB
/
Copy pathplanner.ts
File metadata and controls
1347 lines (1256 loc) · 49.8 KB
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* oxlint-disable executor/no-try-catch-or-throw, executor/no-error-constructor, executor/no-instanceof-error, executor/no-unknown-error-message, executor/no-json-parse -- boundary: one-shot provider service split planner preserves the throwing dry-run contract used by migration tooling */
import { createHash } from "node:crypto";
import {
googleCatalog,
googlePresetForDiscoveryUrl,
} from "@executor-js/plugin-openapi/providers/google";
import {
MICROSOFT_GRAPH_DEFAULT_PRESET_IDS,
microsoftCatalog,
} from "@executor-js/plugin-openapi/providers/microsoft";
import type { OpenApiPreset } from "@executor-js/plugin-openapi/presets";
type MonolithPluginId = "google" | "microsoft";
const normalizeUrl = (url: string): string => {
const trimmed = url.trim();
if (!URL.canParse(trimmed)) return trimmed.replace(/\/$/, "");
const parsed = new URL(trimmed);
parsed.hash = "";
parsed.searchParams.sort();
return parsed.toString().replace(/\/$/, "");
};
const googleCatalogByDiscoveryUrl = new Map(
googleCatalog.flatMap((preset) =>
preset.url ? [[normalizeUrl(preset.url), preset] as const] : [],
),
);
const matchPattern = (pattern: string, toolId: string): boolean => {
if (pattern === "*") return true;
const patternSegments = pattern.split(".");
const toolSegments = toolId.split(".");
for (let index = 0; index < patternSegments.length; index += 1) {
const segment = patternSegments[index]!;
if (segment === "*") {
if (index === patternSegments.length - 1) return toolSegments.length >= index;
if (index >= toolSegments.length) return false;
continue;
}
if (index >= toolSegments.length || toolSegments[index] !== segment) return false;
}
return patternSegments.length === toolSegments.length;
};
export type PluginId = "openapi";
export interface IntegrationRow {
readonly tenant: string;
readonly slug: string;
readonly plugin_id: string;
readonly name: string | null;
readonly description: string | null;
readonly config: unknown;
readonly health_check?: unknown;
readonly config_revised_at?: string | number | bigint | null;
readonly can_remove: boolean;
readonly can_refresh: boolean;
readonly created_at: string;
readonly updated_at: string;
readonly row_id: string;
}
export interface ConnectionRow {
readonly tenant: string;
readonly owner: string;
readonly subject: string;
readonly integration: string;
readonly name: string;
readonly template: string;
readonly provider: string;
readonly item_ids: unknown;
readonly identity_label: string | null;
readonly description?: string | null;
readonly last_health?: unknown;
readonly tools_synced_at?: string | number | bigint | null;
readonly oauth_client: string | null;
readonly oauth_client_owner: string | null;
readonly refresh_item_id: string | null;
readonly expires_at: string | number | bigint | null;
readonly oauth_scope: string | null;
readonly oauth_token_url?: string | null;
readonly provider_state: unknown;
readonly created_at: string;
readonly updated_at: string;
readonly row_id: string;
}
export interface ToolRow {
readonly tenant: string;
readonly owner: string;
readonly subject: string;
readonly integration: string;
readonly connection: string;
readonly plugin_id: string;
readonly name: string;
readonly description?: string;
readonly input_schema?: unknown;
readonly output_schema?: unknown;
readonly annotations?: unknown;
readonly created_at?: string;
readonly updated_at?: string;
readonly row_id: string;
}
export interface PluginStorageRow {
readonly tenant: string;
readonly owner: string;
readonly subject: string;
readonly plugin_id: string;
readonly collection: string;
readonly key: string;
readonly data: unknown;
readonly created_at: string;
readonly updated_at: string;
readonly row_id: string;
}
export interface BlobRow {
readonly id: string;
readonly namespace: string;
readonly key: string;
}
export interface ToolPolicyRow {
readonly tenant: string;
readonly owner: string;
readonly subject: string;
readonly id: string;
readonly pattern: string;
readonly action: string;
readonly position: string;
readonly created_at: string;
readonly updated_at: string;
readonly row_id: string;
}
export interface MigrationInput {
readonly integrations: readonly IntegrationRow[];
readonly connections: readonly ConnectionRow[];
readonly tools: readonly ToolRow[];
readonly pluginStorage?: readonly PluginStorageRow[];
readonly blobs?: readonly BlobRow[];
readonly policies: readonly ToolPolicyRow[];
readonly completedTenants?: readonly string[];
readonly trafficLastTenant?: string;
readonly collectPolicyErrors?: boolean;
readonly orphanPolicyMode?: "hard_error" | "retarget_all";
readonly blobBackend?: "database" | "external";
readonly assumeExternalBlobSourcePresent?: boolean;
readonly bootRailCreateToolImpliedServices?: boolean;
}
export interface ServiceTarget {
readonly family: MonolithPluginId;
readonly pluginId: PluginId;
readonly presetId: string;
readonly slug: string;
readonly name: string;
readonly description: string;
readonly specUrl?: string;
readonly specFormat: "google-discovery" | "microsoft-graph";
readonly authenticationTemplate?: readonly unknown[];
readonly healthCheck?: unknown;
}
export interface PlannedIntegration {
readonly source: Pick<IntegrationRow, "tenant" | "slug" | "plugin_id" | "name">;
readonly sourceContributions: readonly {
readonly source: IntegrationRow;
readonly specHash?: string;
readonly operationsToBuild: number;
readonly operationToolNames: readonly string[];
readonly specBlobPresent: boolean;
readonly defsBlobPresent: boolean;
}[];
readonly target: ServiceTarget;
readonly action: "create" | "skip_existing";
readonly config: unknown;
readonly healthCheck?: unknown;
readonly servingState: {
readonly specHash?: string;
readonly specSource: string;
readonly blobBackend: "database" | "external";
readonly specBlobPresent: boolean;
readonly defsBlobPresent: boolean;
readonly operationsToBuild: number;
readonly operationToolNames: readonly string[];
readonly expectedZeroOperations: boolean;
};
}
export interface PlannedBlobCopy {
readonly source: Pick<IntegrationRow, "tenant" | "slug" | "plugin_id">;
readonly specHash: string;
readonly key: string;
readonly sourceNamespace: string;
readonly targetNamespace: string;
readonly backend: "database" | "external";
readonly sourcePresent: boolean;
readonly targetPresent: boolean;
readonly sourceObjectName: string;
readonly targetObjectName: string;
}
export interface PlannedConnection {
readonly source: Pick<ConnectionRow, "tenant" | "owner" | "subject" | "integration" | "name">;
readonly targetIntegration: string;
readonly action: "clone" | "skip_existing";
readonly tokenReuse: "copy_item_ids_and_oauth_columns";
}
export interface PlannedPolicyRewrite {
readonly policy: Pick<
ToolPolicyRow,
"tenant" | "owner" | "subject" | "id" | "pattern" | "action" | "position"
>;
readonly action: "rewrite";
readonly afterPatterns: readonly string[];
readonly matchedServices: readonly string[];
}
export interface OrgPlan {
readonly tenant: string;
readonly tenantHash: string;
readonly completed: boolean;
readonly integrations: readonly PlannedIntegration[];
readonly connections: readonly PlannedConnection[];
readonly policies: readonly PlannedPolicyRewrite[];
readonly blobCopies: readonly PlannedBlobCopy[];
readonly deleteMonoliths: readonly Pick<
IntegrationRow,
"tenant" | "slug" | "plugin_id" | "name"
>[];
readonly clonedToolRows: number;
readonly operationsToBuild: number;
readonly hardErrors: readonly string[];
}
export interface MigrationPlan {
readonly orgs: readonly OrgPlan[];
readonly summary: {
readonly orgs: number;
readonly completedOrgs: number;
readonly integrationsCreate: number;
readonly integrationsSkipExisting: number;
readonly connectionsClone: number;
readonly connectionsSkipExisting: number;
readonly policiesRewrite: number;
readonly policiesSkip: number;
readonly policyRowsAfter: number;
readonly monolithDeletes: number;
readonly clonedToolRows: number;
readonly operationsToBuild: number;
readonly integrationsMissingSpecBlob: number;
readonly integrationsMissingDefsBlob: number;
readonly hardErrorOrgs: number;
readonly policyHardErrors: number;
};
}
const GOOGLE_IDENTITY_DISCOVERY_URL = "https://www.googleapis.com/discovery/v1/apis/oauth2/v2/rest";
const GOOGLE_TOOL_PREFIX_TO_PRESET_ID: ReadonlyMap<string, string> = new Map([
["calendar", "google-calendar"],
["gmail", "google-gmail"],
["sheets", "google-sheets"],
["drive", "google-drive"],
["docs", "google-docs"],
["slides", "google-slides"],
["forms", "google-forms"],
["tasks", "google-tasks"],
["people", "google-people"],
["photoslibrary", "google-photos-library"],
["photospicker", "google-photos-picker"],
["chat", "google-chat"],
["keep", "google-keep"],
["youtube", "google-youtube-data"],
["searchconsole", "google-search-console"],
["webmasters", "google-search-console"],
["classroom", "google-classroom"],
["directory", "google-admin-directory"],
["reports", "google-admin-reports"],
["script", "google-apps-script"],
["bigquery", "google-bigquery"],
["cloudresourcemanager", "google-cloud-resource-manager"],
]);
const unique = <T>(values: Iterable<T>): readonly T[] => [...new Set(values)];
export const tenantHash = (tenant: string): string =>
createHash("sha256").update(tenant).digest("hex").slice(0, 12);
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
const recordFromJsonLike = (value: unknown): Record<string, unknown> => {
if (isRecord(value)) return value;
if (typeof value !== "string") return {};
try {
const parsed = JSON.parse(value) as unknown;
return isRecord(parsed) ? parsed : {};
} catch {
return {};
}
};
const stringArray = (value: unknown): readonly string[] =>
Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : [];
const configRecord = (integration: IntegrationRow): Record<string, unknown> =>
recordFromJsonLike(integration.config);
const toolAddress = (
tool: Pick<ToolRow, "integration" | "owner" | "connection" | "name">,
): string => `${tool.integration}.${tool.owner}.${tool.connection}.${tool.name}`;
const withoutToolsPrefix = (pattern: string): string =>
pattern.startsWith("tools.") ? pattern.slice("tools.".length) : pattern;
const withOriginalToolsPrefix = (original: string, rewrittenTail: string): string =>
original.startsWith("tools.") ? `tools.${rewrittenTail}` : rewrittenTail;
const integrationPatternSegment = (
pattern: string,
): { readonly prefix: boolean; readonly integration: string } => {
const prefix = pattern.startsWith("tools.");
const tail = prefix ? pattern.slice("tools.".length) : pattern;
return { prefix, integration: tail.split(".")[0] ?? "" };
};
const googleCatalogById: ReadonlyMap<string, OpenApiPreset> = new Map(
googleCatalog.map((preset) => [preset.id, preset]),
);
const microsoftCatalogByMonolithPresetId: ReadonlyMap<string, OpenApiPreset> = new Map(
microsoftCatalog.map((preset) => [preset.id.replace(/^microsoft-/, ""), preset]),
);
const MICROSOFT_UNMIGRATABLE_UMBRELLA_PRESET_IDS = new Set(["me-surface", "users", "groups"]);
const MICROSOFT_TOOL_IMPLIED_PRESET_IDS = new Set(MICROSOFT_GRAPH_DEFAULT_PRESET_IDS);
const microsoftCatalogBackedPresetIds = new Set(
microsoftCatalog
.filter((preset) => preset.defaultSlug && preset.defaultSlug.length > 0)
.map((preset) => preset.id.replace(/^microsoft-/, "")),
);
export const microsoftToolFirstSegmentPresetIds: ReadonlyMap<string, readonly string[]> = new Map([
["chats", ["teams-chat"]],
["chatsChat", ["teams-chat"]],
["communications", ["meetings-calls"]],
["communicationsCall", ["meetings-calls"]],
["communicationsOnlineMeeting", ["meetings-calls"]],
["communicationsPresence", ["meetings-calls"]],
["drives", ["files"]],
["drivesDrive", ["files"]],
["drivesDriveItem", ["files"]],
["groupsDrive", ["files"]],
["groupsDrives", ["files"]],
["groupsOnenote", ["onenote"]],
["groupsTeam", ["teams-channels"]],
["meCalendar", ["calendar"]],
["meCalendarGroups", ["calendar"]],
["meCalendars", ["calendar"]],
["meCalendarView", ["calendar"]],
["meChat", ["teams-chat"]],
["meChats", ["teams-chat"]],
["meContact", ["contacts"]],
["meContactFolder", ["contacts"]],
["meContactFolders", ["contacts"]],
["meContacts", ["contacts"]],
["meDrive", ["files"]],
["meDrives", ["files"]],
["meEvent", ["calendar"]],
["meEvents", ["calendar"]],
["meFindMeetingTimes", ["calendar"]],
["meFollowedSites", ["files"]],
["meGetMailTips", ["mail"]],
["meInferenceClassification", ["mail"]],
["meJoinedTeams", ["teams-channels"]],
["meMailFolder", ["mail"]],
["meMailFolders", ["mail"]],
["meMailboxSettings", ["mail"]],
["meMessage", ["mail"]],
["meMessages", ["mail"]],
["meOnlineMeeting", ["meetings-calls"]],
["meOnlineMeetings", ["meetings-calls"]],
["meOnenote", ["onenote"]],
["meOutlook", ["mail"]],
["meOutlookUser", ["mail"]],
["mePeople", ["contacts"]],
["mePerson", ["contacts"]],
["mePhoto", ["profile"]],
["meProfilePhoto", ["profile"]],
["meReminderView", ["calendar"]],
["meSendMail", ["mail"]],
["meSite", ["files"]],
["meTeam", ["teams-channels"]],
["meTodo", ["tasks"]],
["meUser", ["profile"]],
["meUserActions", ["profile"]],
["meUserFunctions", ["profile"]],
["shares", ["files"]],
["sites", ["sites"]],
["sitesOnenote", ["onenote"]],
["sitesSite", ["sites"]],
["teams", ["teams-channels"]],
["teamsChannel", ["teams-channels"]],
["teamsTeam", ["teams-channels"]],
["teamsTemplates", ["teams-channels"]],
["teamwork", ["teams-channels"]],
["usersCalendar", ["calendar"]],
["usersCalendarGroups", ["calendar"]],
["usersCalendars", ["calendar"]],
["usersCalendarView", ["calendar"]],
["usersContact", ["contacts"]],
["usersContactFolder", ["contacts"]],
["usersContactFolders", ["contacts"]],
["usersContacts", ["contacts"]],
["usersDrive", ["files"]],
["usersDrives", ["files"]],
["usersEvent", ["calendar"]],
["usersEvents", ["calendar"]],
["usersFindMeetingTimes", ["calendar"]],
["usersMailFolder", ["mail"]],
["usersMailFolders", ["mail"]],
["usersMessage", ["mail"]],
["usersMessages", ["mail"]],
["usersOnlineMeeting", ["meetings-calls"]],
["usersOnlineMeetings", ["meetings-calls"]],
["usersOnenote", ["onenote"]],
["usersOutlook", ["mail"]],
["usersPeople", ["contacts"]],
["usersPerson", ["contacts"]],
["usersReminderView", ["calendar"]],
["usersSendMail", ["mail"]],
["usersTodo", ["tasks"]],
["usersUser", ["profile"]],
["usersUserActions", ["profile"]],
["usersUserFunctions", ["profile"]],
]);
const MICROSOFT_WORKBOOK_FIRST_SEGMENTS = new Set([
"drivesDriveItem",
"groupsDrive",
"meDrive",
"usersDrive",
]);
const microsoftFirstSegmentOwnershipKey = (firstSegment: string): string | undefined =>
[...microsoftToolFirstSegmentPresetIds.keys()]
.filter(
(key) =>
firstSegment === key ||
(firstSegment.startsWith(key) &&
firstSegment[key.length]?.toUpperCase() === firstSegment[key.length]),
)
.sort((left, right) => right.length - left.length)[0];
const serviceSlugForPreset = (family: MonolithPluginId, presetId: string): string | undefined => {
const preset =
family === "google"
? googleCatalogById.get(presetId)
: microsoftCatalogByMonolithPresetId.get(presetId);
return preset?.defaultSlug;
};
const serviceTargetForPreset = (
family: MonolithPluginId,
presetId: string,
): ServiceTarget | undefined => {
if (family === "google") {
const preset = googleCatalogById.get(presetId);
if (!preset) return undefined;
return {
family,
pluginId: "openapi",
presetId,
slug: preset.defaultSlug ?? preset.id,
name: preset.name,
description: preset.summary,
...(preset.url ? { specUrl: preset.url } : {}),
specFormat: "google-discovery",
...(preset.authTemplate ? { authenticationTemplate: preset.authTemplate } : {}),
...(preset.healthCheck ? { healthCheck: preset.healthCheck } : {}),
};
}
const preset = microsoftCatalogByMonolithPresetId.get(presetId);
if (!preset) return undefined;
return {
family,
pluginId: "openapi",
presetId,
slug: preset.defaultSlug ?? preset.id,
name: preset.name,
description: preset.summary,
...(preset.url ? { specUrl: preset.url } : {}),
specFormat: "microsoft-graph",
...(preset.authTemplate ? { authenticationTemplate: preset.authTemplate } : {}),
...(preset.healthCheck ? { healthCheck: preset.healthCheck } : {}),
};
};
const googlePresetIdsFromConfig = (integration: IntegrationRow): readonly string[] => {
const urls = stringArray(configRecord(integration).googleDiscoveryUrls);
return unique(
urls.flatMap((url) => {
if (url === GOOGLE_IDENTITY_DISCOVERY_URL || url.includes("/oauth2/")) return [];
const preset =
googleCatalogByDiscoveryUrl.get(normalizeUrl(url)) ?? googlePresetForDiscoveryUrl(url);
return preset ? [preset.id] : [];
}),
);
};
const microsoftPresetIdsFromConfig = (integration: IntegrationRow): readonly string[] => {
const config = configRecord(integration);
const configured = [
...stringArray(config.microsoftGraphPresetIds),
...stringArray(config.microsoftGraphScopePresetIds),
];
if (configured.length > 0) return unique(configured);
throw new Error(
`Microsoft monolith ${tenantHash(integration.tenant)}/${integration.slug} has no stored microsoftGraphPresetIds; refusing to fabricate ${MICROSOFT_GRAPH_DEFAULT_PRESET_IDS.length} default workloads`,
);
};
const microsoftUnmigratablePresetIds = (presetIds: readonly string[]): readonly string[] =>
presetIds.filter(
(presetId) =>
MICROSOFT_UNMIGRATABLE_UMBRELLA_PRESET_IDS.has(presetId) ||
!microsoftCatalogBackedPresetIds.has(presetId),
);
export const googlePresetIdForTool = (toolName: string): string | undefined => {
const [first, second] = toolName.split(".");
if (first === "admin") {
return second === "channels" ? "google-admin-reports" : "google-admin-directory";
}
return GOOGLE_TOOL_PREFIX_TO_PRESET_ID.get(first ?? "");
};
export const microsoftPresetIdsForTool = (toolName: string): readonly string[] => {
const segments = toolName.split(".");
const first = segments[0] ?? "";
const ownershipKey = microsoftFirstSegmentOwnershipKey(first);
const fromFirstSegment = ownershipKey
? (microsoftToolFirstSegmentPresetIds.get(ownershipKey) ?? [])
: [];
const workbookOwned =
ownershipKey !== undefined &&
MICROSOFT_WORKBOOK_FIRST_SEGMENTS.has(ownershipKey) &&
segments.some((segment) => segment.toLowerCase().includes("workbook"));
return unique([...fromFirstSegment, ...(workbookOwned ? ["excel"] : [])]).filter((presetId) =>
MICROSOFT_TOOL_IMPLIED_PRESET_IDS.has(presetId),
);
};
const presetIdsForTool = (pluginId: MonolithPluginId, toolName: string): readonly string[] => {
const presetId = pluginId === "google" ? googlePresetIdForTool(toolName) : undefined;
return pluginId === "google" ? (presetId ? [presetId] : []) : microsoftPresetIdsForTool(toolName);
};
const deriveServices = (
integration: IntegrationRow,
tools: readonly ToolRow[],
bootRailCreateToolImpliedServices: boolean,
): readonly ServiceTarget[] => {
const pluginId = integration.plugin_id as MonolithPluginId;
const fromConfig =
pluginId === "google"
? googlePresetIdsFromConfig(integration)
: microsoftPresetIdsFromConfig(integration);
if (pluginId === "microsoft") {
const unmigratablePresetIds = microsoftUnmigratablePresetIds(fromConfig);
if (unmigratablePresetIds.length > 0) {
throw new Error(
`Monolith ${tenantHash(integration.tenant)}/${integration.plugin_id}/${integration.slug} references unmigratable-umbrella Microsoft Graph preset(s): ${unmigratablePresetIds.join(", ")}; org needs manual handling`,
);
}
}
const fromTools = unique(
tools.flatMap((tool) => {
const presetIds = presetIdsForTool(pluginId, tool.name);
if (
pluginId === "microsoft" &&
fromConfig.length > 0 &&
presetIds.some((presetId) => fromConfig.includes(presetId))
) {
return [];
}
return presetIds;
}),
);
const missingToolPresetIds = fromTools.filter((presetId) => !fromConfig.includes(presetId));
if (
fromConfig.length > 0 &&
missingToolPresetIds.length > 0 &&
!bootRailCreateToolImpliedServices
) {
throw new Error(
`Monolith ${tenantHash(integration.tenant)}/${integration.plugin_id}/${integration.slug} config omits tool-implied service preset(s): ${missingToolPresetIds.join(", ")}`,
);
}
const presetIds =
bootRailCreateToolImpliedServices && fromConfig.length > 0
? unique([...fromConfig, ...fromTools])
: fromConfig.length > 0
? fromConfig
: fromTools;
const services = presetIds.flatMap(
(presetId) => serviceTargetForPreset(pluginId, presetId) ?? [],
);
const missingCatalogPresetIds = presetIds.filter(
(presetId) => !serviceTargetForPreset(pluginId, presetId),
);
if (missingCatalogPresetIds.length > 0) {
throw new Error(
`Monolith ${tenantHash(integration.tenant)}/${integration.plugin_id}/${integration.slug} references unknown service preset(s): ${missingCatalogPresetIds.join(", ")}`,
);
}
if (services.length === 0) {
throw new Error(
`Monolith ${tenantHash(integration.tenant)}/${integration.plugin_id}/${integration.slug} has no derivable services`,
);
}
return services;
};
const configForService = (source: IntegrationRow, target: ServiceTarget): unknown => {
const config = configRecord(source);
const specHash =
typeof config.specHash === "string" && config.specHash.length > 0 ? config.specHash : undefined;
return {
...(specHash ? { specHash } : {}),
...(target.specUrl ? { specUrl: target.specUrl } : {}),
specFormat: target.specFormat,
family: target.family,
...(target.authenticationTemplate
? { authenticationTemplate: target.authenticationTemplate }
: {}),
};
};
const rowKey = (...parts: readonly string[]): string => parts.join("\u0000");
const stableKeyHash = (value: string): string => {
let hash = 0xcbf29ce484222325n;
const prime = 0x100000001b3n;
const mask = 0xffffffffffffffffn;
for (let index = 0; index < value.length; index += 1) {
hash ^= BigInt(value.charCodeAt(index));
hash = (hash * prime) & mask;
}
return hash.toString(36).padStart(13, "0");
};
export const operationStorageKey = (integration: string, toolName: string): string =>
`op.${stableKeyHash(integration)}.${stableKeyHash(toolName)}`;
export const storageDataRecord = (row: Pick<PluginStorageRow, "data">): Record<string, unknown> =>
recordFromJsonLike(row.data);
const operationToolName = (row: PluginStorageRow): string | undefined => {
const value = storageDataRecord(row).toolName;
return typeof value === "string" && value.length > 0 ? value : undefined;
};
const operationIntegration = (row: PluginStorageRow): string | undefined => {
const value = storageDataRecord(row).integration;
return typeof value === "string" && value.length > 0 ? value : undefined;
};
const specHashFor = (integration: IntegrationRow): string => {
const value = configRecord(integration).specHash;
if (typeof value === "string" && value.length > 0) return value;
throw new Error(
`Monolith ${tenantHash(integration.tenant)}/${integration.plugin_id}/${integration.slug} has no specHash; serving state cannot be migrated`,
);
};
const pluginBlobNamespace = (tenant: string, pluginId: string): string => `o:${tenant}/${pluginId}`;
const blobObjectName = (namespace: string, key: string): string => `${namespace}/${key}`;
const operationRowsForService = (
monolith: IntegrationRow,
target: ServiceTarget,
rows: readonly PluginStorageRow[],
): readonly PluginStorageRow[] =>
rows.filter((row) => {
if (row.tenant !== monolith.tenant) return false;
if (row.plugin_id !== monolith.plugin_id) return false;
if (row.collection !== "operation") return false;
if (operationIntegration(row) !== monolith.slug) return false;
const toolName = operationToolName(row);
if (!toolName) return false;
if (isIntentionallyDroppedTool(monolith.plugin_id as MonolithPluginId, toolName)) return false;
return serviceForMatchedTool(monolith.plugin_id as MonolithPluginId, toolName, [
target,
]).includes(target.slug);
});
const operationRowsForMonolith = (
monolith: IntegrationRow,
rows: readonly PluginStorageRow[],
): readonly PluginStorageRow[] =>
rows.filter((row) => {
if (row.tenant !== monolith.tenant) return false;
if (row.plugin_id !== monolith.plugin_id) return false;
if (row.collection !== "operation") return false;
return operationIntegration(row) === monolith.slug;
});
const isConfigOnlyMonolith = (input: {
readonly tools: readonly ToolRow[];
readonly connections: readonly ConnectionRow[];
readonly operations: readonly PluginStorageRow[];
}): boolean =>
input.tools.length === 0 && input.connections.length === 0 && input.operations.length === 0;
const isIntentionallyDroppedTool = (pluginId: MonolithPluginId, toolName: string): boolean =>
pluginId === "google" && toolName.startsWith("oauth2.");
const serviceForMatchedTool = (
pluginId: MonolithPluginId,
toolName: string,
services: readonly ServiceTarget[],
): readonly string[] => {
const presetIds = presetIdsForTool(pluginId, toolName);
return presetIds.flatMap((presetId) => {
const slug = serviceSlugForPreset(pluginId, presetId);
return slug && services.some((service) => service.slug === slug) ? [slug] : [];
});
};
const allServiceSlugs = (services: readonly ServiceTarget[]): readonly string[] =>
services.map((service) => service.slug);
const unassignedToolNames = (
pluginId: MonolithPluginId,
tools: readonly { readonly name: string }[],
services: readonly ServiceTarget[],
): readonly string[] =>
unique(
tools.flatMap((tool) => {
if (isIntentionallyDroppedTool(pluginId, tool.name)) return [];
return serviceForMatchedTool(pluginId, tool.name, services).length === 0 ? [tool.name] : [];
}),
);
const assertNoUnassignedRows = (
monolith: IntegrationRow,
tools: readonly ToolRow[],
operations: readonly PluginStorageRow[],
services: readonly ServiceTarget[],
): void => {
const pluginId = monolith.plugin_id as MonolithPluginId;
const unassignedTools = unassignedToolNames(pluginId, tools, services);
if (unassignedTools.length > 0) {
throw new Error(
`Monolith ${tenantHash(monolith.tenant)}/${monolith.plugin_id}/${monolith.slug} has tool row(s) with no target service: ${unassignedTools.slice(0, 20).join(", ")}`,
);
}
const operationTools = operations.flatMap((row) => {
const toolName = operationToolName(row);
return toolName ? [{ name: toolName }] : [];
});
const unassignedOperations = unassignedToolNames(pluginId, operationTools, services);
if (unassignedOperations.length > 0) {
throw new Error(
`Monolith ${tenantHash(monolith.tenant)}/${monolith.plugin_id}/${monolith.slug} has operation row(s) with no target service: ${unassignedOperations.slice(0, 20).join(", ")}`,
);
}
};
const serviceSlugsForToolPattern = (
pluginId: MonolithPluginId,
toolSegments: readonly string[],
services: readonly ServiceTarget[],
): readonly string[] => {
const firstToolSegment = toolSegments[0];
if (!firstToolSegment || firstToolSegment === "*") return allServiceSlugs(services);
const presetIds = presetIdsForTool(pluginId, toolSegments.join("."));
return presetIds.flatMap((presetId) => {
const slug = serviceSlugForPreset(pluginId, presetId);
return slug && services.some((service) => service.slug === slug) ? [slug] : [];
});
};
const serviceSlugsForPolicyPattern = (
policy: ToolPolicyRow,
monolith: IntegrationRow,
services: readonly ServiceTarget[],
): readonly string[] => {
const tail = withoutToolsPrefix(policy.pattern);
const segments = tail.split(".");
const rest = segments.slice(1);
const pluginId = monolith.plugin_id as MonolithPluginId;
if (rest.length === 0) return allServiceSlugs(services);
if (rest[0] === "org" || rest[0] === "user") {
return serviceSlugsForToolPattern(pluginId, rest.slice(2), services);
}
if (rest[0] === "*") {
if (rest.length <= 2) return allServiceSlugs(services);
return serviceSlugsForToolPattern(pluginId, rest.slice(2), services);
}
return serviceSlugsForToolPattern(pluginId, rest, services);
};
const rewritePatternIntegration = (pattern: string, targetSlug: string): string => {
const hasTools = pattern.startsWith("tools.");
const tail = hasTools ? pattern.slice("tools.".length) : pattern;
const segments = tail.split(".");
segments[0] = targetSlug;
return withOriginalToolsPrefix(pattern, segments.join("."));
};
const policyMatches = (pattern: string, tool: ToolRow): boolean => {
const normalized = withoutToolsPrefix(pattern);
return matchPattern(normalized, toolAddress(tool));
};
const rewritePolicy = (
policy: ToolPolicyRow,
monolith: IntegrationRow,
services: readonly ServiceTarget[],
orphanPolicyMode: MigrationInput["orphanPolicyMode"],
): PlannedPolicyRewrite => {
const patternIntegration = integrationPatternSegment(policy.pattern).integration;
if (patternIntegration !== monolith.slug) {
throw new Error(
`Policy ${policy.id} for org ${tenantHash(policy.tenant)} does not target ${monolith.slug}`,
);
}
// Orphan policies (pattern targets a service the org never derived) retarget
// to every derived service as dormant rows: block/require_approval so the
// guardrail intent survives a later add of that service, and approve because
// dropping it is the only alternative and a dormant row is equally inert.
const serviceSlugs = unique(serviceSlugsForPolicyPattern(policy, monolith, services));
const orphanPolicyRetarget = orphanPolicyMode === "retarget_all" ? allServiceSlugs(services) : [];
if (serviceSlugs.length === 0 && orphanPolicyRetarget.length === 0) {
throw new Error(
`Policy ${policy.id} (${policy.pattern}) for org ${tenantHash(policy.tenant)} would be dropped; no target service could be derived`,
);
}
const matchedServices = serviceSlugs.length > 0 ? serviceSlugs : orphanPolicyRetarget;
return {
policy,
action: "rewrite",
afterPatterns: matchedServices.map((slug) => rewritePatternIntegration(policy.pattern, slug)),
matchedServices,
};
};
export interface NeverWidenResult {
readonly ok: boolean;
readonly checkedPolicies: number;
readonly widened: readonly {
readonly policyId: string;
readonly beforePattern: string;
readonly afterPatterns: readonly string[];
readonly extraAddresses: readonly string[];
}[];
readonly narrowed: readonly {
readonly policyId: string;
readonly beforePattern: string;
readonly missingServices: readonly string[];
}[];
}
export const verifyPolicyRewriteNeverWidens = (
plan: MigrationPlan,
input: Pick<MigrationInput, "tools">,
): NeverWidenResult => {
const widened: {
readonly policyId: string;
readonly beforePattern: string;
readonly afterPatterns: readonly string[];
readonly extraAddresses: readonly string[];
}[] = [];
const narrowed: {
readonly policyId: string;
readonly beforePattern: string;
readonly missingServices: readonly string[];
}[] = [];
let checkedPolicies = 0;
for (const org of plan.orgs) {
const orgTools = input.tools.filter((tool) => tool.tenant === org.tenant);
for (const policy of org.policies) {
if (policy.action !== "rewrite") continue;
checkedPolicies += 1;
if (policy.policy.action === "block" || policy.policy.action === "require_approval") {
const afterServices = new Set(
policy.afterPatterns.map(
(afterPattern) => integrationPatternSegment(afterPattern).integration,
),
);
const missingServices = policy.matchedServices.filter((service) => {
if (!afterServices.has(service)) return true;
const expectedPattern = rewritePatternIntegration(policy.policy.pattern, service);
return !policy.afterPatterns.includes(expectedPattern);
});
if (missingServices.length > 0) {
narrowed.push({
policyId: policy.policy.id,
beforePattern: policy.policy.pattern,
missingServices,
});
}
}
const before = new Set(
orgTools
.filter((tool) => policyMatches(policy.policy.pattern, tool))
.flatMap((tool) => {
const monolith = org.deleteMonoliths.find((row) => row.slug === tool.integration);
if (!monolith) return [];
const services = policy.matchedServices.filter((slug) =>
serviceForMatchedTool(
monolith.plugin_id as MonolithPluginId,
tool.name,
org.integrations.map((i) => i.target),
).includes(slug),
);
return services.map((slug) => `${slug}.${tool.owner}.${tool.connection}.${tool.name}`);
}),
);
const after = new Set(
orgTools.flatMap((tool) => {
const monolith = org.deleteMonoliths.find((row) => row.slug === tool.integration);
if (!monolith) return [];
const toolServices = serviceForMatchedTool(
monolith.plugin_id as MonolithPluginId,
tool.name,
org.integrations.map((integration) => integration.target),
);
return policy.afterPatterns
.filter((afterPattern) => {
const targetSlug = integrationPatternSegment(afterPattern).integration;
if (!toolServices.includes(targetSlug)) return false;
const targetTool = { ...tool, integration: targetSlug };
return policyMatches(afterPattern, targetTool);
})
.map((afterPattern) => {
const targetSlug = integrationPatternSegment(afterPattern).integration;
return `${targetSlug}.${tool.owner}.${tool.connection}.${tool.name}`;
});
}),
);
const extra = [...after].filter((address) => !before.has(address));
if (extra.length > 0) {
widened.push({
policyId: policy.policy.id,
beforePattern: policy.policy.pattern,
afterPatterns: policy.afterPatterns,
extraAddresses: extra.slice(0, 20),
});
}
}
}
return {
ok: widened.length === 0 && narrowed.length === 0,
checkedPolicies,
widened,
narrowed,
};
};
export const planMigration = (input: MigrationInput): MigrationPlan => {
const completed = new Set(input.completedTenants ?? []);
const monoliths = input.integrations.filter(
(row) => row.plugin_id === "google" || row.plugin_id === "microsoft",
);
const tenants = [...unique(monoliths.map((row) => row.tenant))].sort();
const trafficLastTenant = input.trafficLastTenant;
const orderedTenants = trafficLastTenant
? [
...tenants.filter((tenant) => tenant !== trafficLastTenant),
...tenants.filter((tenant) => tenant === trafficLastTenant),
]
: tenants;
const integrationExists = new Set(input.integrations.map((row) => rowKey(row.tenant, row.slug)));
const blobBackend = input.blobBackend ?? "database";
const connectionExists = new Set(
input.connections.map((row) =>
rowKey(row.tenant, row.owner, row.subject, row.integration, row.name),
),
);
const orgs = orderedTenants.map((tenant): OrgPlan => {