-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
external.ts
390 lines (353 loc) · 12.5 KB
/
external.ts
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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { ChannelCredentials } from "@grpc/grpc-js";
import { GrpcTransport } from "@protobuf-ts/grpc-transport";
import { Writer } from "protobufjs";
import {
ExpansionRequest,
ExpansionResponse,
} from "../proto/beam_expansion_api";
import {
ExpansionServiceClient,
IExpansionServiceClient,
} from "../proto/beam_expansion_api.client";
import {
ArtifactRetrievalServiceClient,
IArtifactRetrievalServiceClient,
} from "../proto/beam_artifact_api.client";
import * as runnerApi from "../proto/beam_runner_api";
import { ExternalConfigurationPayload } from "../proto/external_transforms";
import { Schema } from "../proto/schema";
import { PValue, PCollection } from "../pvalue";
import { Pipeline } from "../internal/pipeline";
import * as coders from "../coders/standard_coders";
import * as internal from "./internal";
import * as transform from "./transform";
import { RowCoder } from "../coders/row_coder";
import { Coder } from "../coders/coders";
import * as artifacts from "../runners/artifacts";
import * as service from "../utils/service";
/**
* Various transforms useful for creating and invoking cross-language
* transforms.
*
* See also https://beam.apache.org/documentation/programming-guide/#1324-using-cross-language-transforms-in-a-typescript-pipeline
*
* @packageDocumentation
*/
export interface RawExternalTransformOptions {
inferPValueType?: boolean;
requestedOutputCoders?: { [key: string]: Coder<unknown> };
}
const defaultRawExternalTransformOptions: RawExternalTransformOptions = {
inferPValueType: true,
requestedOutputCoders: {},
};
// TODO: (API) (Types) This class expects PCollections to already have the
// correct Coders. It would be great if we could infer coders, or at least have
// a cleaner way to specify them than using internal.WithCoderInternal.
export function rawExternalTransform<
InputT extends PValue<any>,
OutputT extends PValue<any>,
>(
urn: string,
payload: Uint8Array | { [key: string]: any },
serviceProviderOrAddress: string | (() => Promise<service.Service>),
options: RawExternalTransformOptions = {},
): transform.AsyncPTransform<InputT, OutputT> {
return new RawExternalTransform(
urn,
payload,
serviceProviderOrAddress,
options,
);
}
class RawExternalTransform<
InputT extends PValue<any>,
OutputT extends PValue<any>,
> extends transform.AsyncPTransformClass<InputT, OutputT> {
static namespaceCounter = 0;
static freshNamespace() {
return "namespace_" + RawExternalTransform.namespaceCounter++ + "_";
}
private payload?: Uint8Array;
private serviceProvider: () => Promise<service.Service>;
private options: RawExternalTransformOptions;
constructor(
private urn: string,
payload: Uint8Array | { [key: string]: any },
serviceProviderOrAddress: string | (() => Promise<service.Service>),
options: RawExternalTransformOptions,
) {
super("External(" + urn + ")");
this.options = { ...defaultRawExternalTransformOptions, ...options };
if (payload === null || payload === undefined) {
this.payload = undefined;
} else if (payload instanceof Uint8Array) {
this.payload = payload as Uint8Array;
} else {
this.payload = encodeSchemaPayload(payload);
}
if (typeof serviceProviderOrAddress === "string") {
this.serviceProvider = async () =>
new service.ExternalService(serviceProviderOrAddress);
} else {
this.serviceProvider = serviceProviderOrAddress;
}
}
async expandInternalAsync(
input: InputT,
pipeline: Pipeline,
transformProto: runnerApi.PTransform,
): Promise<OutputT> {
const pipelineComponents = pipeline.getProto().components!;
const namespace = RawExternalTransform.freshNamespace();
const request = ExpansionRequest.create({
transform: runnerApi.PTransform.create({
uniqueName: transformProto.uniqueName,
spec: { urn: this.urn, payload: this.payload },
inputs: transformProto.inputs,
}),
components: {},
namespace: namespace,
});
// Some SDKs are not happy with PCollections created out of thin air.
const fakeImpulseNamespace = RawExternalTransform.freshNamespace();
for (const pcId of Object.values(transformProto.inputs)) {
request.components!.pcollections[pcId] =
pipelineComponents.pcollections![pcId];
request.components!.transforms[fakeImpulseNamespace + pcId] =
runnerApi.PTransform.create({
uniqueName: fakeImpulseNamespace + "_create_" + pcId,
spec: { urn: internal.impulse.urn, payload: new Uint8Array() },
outputs: { main: pcId },
});
}
for (const [output, coder] of Object.entries(
this.options.requestedOutputCoders!,
)) {
request.outputCoderRequests[output] = pipeline.getCoderId(coder);
}
// Copy all the rest, as there may be opaque references.
Object.assign(request.components!.coders, pipelineComponents.coders);
Object.assign(
request.components!.windowingStrategies,
pipelineComponents.windowingStrategies,
);
Object.assign(
request.components!.environments,
pipelineComponents.environments,
);
const service = await this.serviceProvider();
const address = await service.start();
const client = new ExpansionServiceClient(
new GrpcTransport({
host: address,
channelCredentials: ChannelCredentials.createInsecure(),
}),
);
try {
const response = await client.expand(request).response;
if (response.error) {
throw new Error(response.error);
}
response.components = await this.resolveArtifacts(
response.components!,
address,
);
return this.splice(pipeline, transformProto, response, namespace);
} finally {
await service.stop();
}
}
/**
* The returned pipeline fragment may have dependencies (referenced in its)
* environments) that are needed for execution. This function fetches (as
* required) these artifacts from the expansion service (which may be
* be transient) and stores them in files such that it may then forward
* these artifacts to the choice of runner.
*/
async resolveArtifacts(
components: runnerApi.Components,
address: string,
): Promise<runnerApi.Components> {
// Don't even bother creating a connection if there are no dependencies.
if (
Object.values(components.environments).every(
(env) => env.dependencies.length === 0,
)
) {
return components;
}
// An expansion service that returns environments with dependencies must
// aslo vend an artifact retrieval service as that same port.
const artifactClient = new ArtifactRetrievalServiceClient(
new GrpcTransport({
host: address,
channelCredentials: ChannelCredentials.createInsecure(),
}),
);
// For each new environment, convert (if needed) all dependencies into
// a more permanent form.
for (const env of Object.values(components.environments)) {
if (env.dependencies.length > 0) {
env.dependencies = Array.from(
await (async () => {
let result: runnerApi.ArtifactInformation[] = [];
for await (const dep of artifacts.resolveArtifacts(
artifactClient,
env.dependencies,
)) {
result.push(dep);
}
return result;
})(),
);
}
}
return components;
}
splice(
pipeline: Pipeline,
transformProto: runnerApi.PTransform,
response: ExpansionResponse,
namespace: string,
): OutputT {
function copyNamespaceComponents<T>(
src: { [key: string]: T },
dest: { [key: string]: T },
) {
for (const [id, proto] of Object.entries(src)) {
if (id.startsWith(namespace)) {
dest[id] = proto;
}
}
}
function difference<T>(a: Set<T>, b: Set<T>): T[] {
return [...a].filter((x) => !b.has(x));
}
// Some SDKs enforce input naming conventions.
const newTags = difference(
new Set(Object.keys(response.transform!.inputs)),
new Set(Object.keys(transformProto.inputs)),
);
if (newTags.length > 1) {
throw new Error("Ambiguous renaming of tags.");
} else if (newTags.length === 1) {
const missingTags = difference(
new Set(Object.keys(transformProto.inputs)),
new Set(Object.keys(response.transform!.inputs)),
);
transformProto.inputs[newTags[0]] = transformProto.inputs[missingTags[0]];
delete transformProto.inputs[missingTags[0]];
}
// PCollection ids may have changed as well.
const renamedInputs = Object.fromEntries(
Object.keys(response.transform!.inputs).map((k) => [
response.transform!.inputs[k],
transformProto.inputs[k],
]),
);
response.transform!.inputs = Object.fromEntries(
Object.entries(response.transform!.inputs).map(([k, v]) => [
k,
renamedInputs[v],
]),
);
for (const t of Object.values(response.components!.transforms)) {
t.inputs = Object.fromEntries(
Object.entries(t.inputs).map(([k, v]) => [
k,
renamedInputs[v] !== null && renamedInputs[v] !== undefined
? renamedInputs[v]
: v,
]),
);
}
// Copy the proto contents.
Object.assign(transformProto, response.transform);
// Now copy everything over.
const proto = pipeline.getProto();
const pipelineComponents = proto.components;
pipeline.getProto().requirements.push(...response.requirements);
copyNamespaceComponents(
response.components!.transforms,
pipelineComponents!.transforms,
);
copyNamespaceComponents(
response.components!.pcollections,
pipelineComponents!.pcollections,
);
copyNamespaceComponents(
response.components!.coders,
pipelineComponents!.coders,
);
copyNamespaceComponents(
response.components!.environments,
pipelineComponents!.environments,
);
copyNamespaceComponents(
response.components!.windowingStrategies,
pipelineComponents!.windowingStrategies,
);
// Ensure we understand the resulting coders.
// TODO: We could still patch things together if we don't understand the coders,
// but the errors are harder to follow. Consider only rejecting coders that
// actually cross the boundary.
for (const pcId of Object.values(response.transform!.outputs)) {
const pcProto = pipelineComponents!.pcollections[pcId];
pipeline.context.getCoder(pcProto.coderId);
}
// Construct and return the resulting object.
// TODO: (Typescipt) Can I get the concrete OutputT at runtime?
// TypeScript types are not available at runtime. If I understand correctly, there is no plan to change that at the moment.
// See: https://github.com/microsoft/TypeScript/issues/47658
// See: https://github.com/microsoft/TypeScript/issues/3628
if (this.options.inferPValueType) {
const outputKeys = [...Object.keys(response.transform!.outputs)];
if (outputKeys.length === 0) {
return null!;
} else if (outputKeys.length === 1) {
return new PCollection(
pipeline,
response.transform!.outputs[outputKeys[0]],
) as OutputT;
}
}
return Object.fromEntries(
Object.entries(response.transform!.outputs).map(([k, v]) => [
k,
new PCollection(pipeline, v),
]),
) as OutputT;
}
}
function encodeSchemaPayload(
payload: any,
schema: Schema | undefined = undefined,
): Uint8Array {
const encoded = new Writer();
if (!schema) {
schema = RowCoder.inferSchemaOfJSON(payload);
}
new RowCoder(schema!).encode(payload, encoded, null!);
return ExternalConfigurationPayload.toBinary({
schema: schema,
payload: encoded.finish(),
});
}