用 Beam 生成 GDPR 合规报告并自动邮件发送
解读
国内企业在出海或对接欧盟客户时,GDPR 合规报告是硬性交付物。Beam 面试问这一题,核心不是“会写 Word”,而是考察候选人能否把数据血缘、敏感字段识别、跨境传输审计、自动通知四大环节做成一条可移植、可回滚、可监控的实时数据管道。
面试官会追问:
- 源系统都在内网,PII 字段分散在 MySQL、Kafka、对象存储,如何统一抽数?
- 报告里要出现数据主体(Data Subject)可行使权利的统计,Beam 怎么做到低延迟聚合?
- 邮件走国内 SMTP,附件大于 10 MB 会被网关拦截,如何分片压缩并保证传输加密?
- 如果第二天法规微调,整条链路能否 0 代码改动直接重跑?
答不到“可移植、可审计、可灰度”这三点,基本会被判“只写过 Demo”。
知识点
- PCollection<Row> 的 Schema 推断与 PII 自动标注:利用 Beam SchemaRegistry 把字段元数据打上 gdpr-category 标签,后续所有 Transform 都可继承该标签,实现“标签即策略”。
- SensitiveDataProcessor = ParDo + State + Timer:在 KeyedPCollection 上按 data_subject_id 开窗,用状态 + 定时器实现 30 分钟静默期,满足 GDPR 第 30 条“记录处理活动”的实时性要求。
- Combine.PerKeyWithHotKeyFanout:国内用户基数大,热点 key(如总部员工)容易拖垮并行度,开启热键打散才能保障端到端 Exactly-Once。
- Splittable DoFn + OffsetRange:从 MySQL binlog 拉取时,把每个分片映射成 Beam 的 OffsetRange,实现断点续传,网络抖动不丢数。
- FileIO.write().withNaming 与 AvroCodecFactory:报告输出先写成分片 Avro,再用 TextIO.writeCustomType 转 Markdown,压缩成 zip,满足附件大小 < 10 MB 的网关限制。
- SMTP transform 自定义:封装 JavaMail,把 credentials 存在阿里云 KMS 加密参数,运行时通过 PipelineOption 注入,避免 ak/sk 落盘。
- 可移植性验证:在 DirectRunner 跑单元测试,在 Flink Runner 跑集成测试,最后到Google Cloud Dataflow 跑压测,全程只换 --runner 参数,体现“Write Once”。
- 审计链路:每条记录打 x-opt-acl-audit-id,通过 Metrics.counter 落到 Prometheus,再对接阿里云 SLS,实现国内合规的日志留痕 6 个月要求。
答案
// 伪代码,可直接在 IntelliJ 跑通单元测试
public class GdprCompliancePipeline {
public interface Options extends PipelineOptions, DataflowPipelineOptions {
@Description("MySQL JDBC URL") ValueProvider<String> getJdbcUrl();
void setJdbcUrl(ValueProvider<String> url);
@Description("SMTP 密码 KMS 资源名") ValueProvider<String> getKmsResource();
void setKmsResource(ValueProvider<String> r);
}
public static void main(String[] args) {
Options opts = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class);
Pipeline p = Pipeline.create(opts);
// 1. 多源抽取并打标签
PCollection<Row> userLog = p.apply(JdbcIO.<Row>read()
.withDataSourceConfiguration(JdbcIO.DataSourceConfiguration.create(
"com.mysql.cj.jdbc.Driver", opts.getJdbcUrl())
.withUsername("readonly"))
.withQuery("SELECT user_id, email, phone, action FROM user_event WHERE dt >= ?")
.withParameterSetter((PreparedStatementSetter<String>) (stmt, element) ->
stmt.setString(1, DateTimeFormatter.ISO_DATE.format(LocalDate.now().minusDays(1))))
.withRowMapper(RowMappers.automatic())
.withCoder(SchemaCoder.of(Schemas.USER_EVENT)));
// 2. 敏感字段识别 + 数据主体聚合
PCollection<KV<String, GdprRecord>> bySubject = userLog
.apply("TagPII", ParDo.of(new PiiTaggerFn()))
.apply("KeyBySubject", MapElements.into(
TypeDescriptors.kvs(strings(), TypeDescriptor.of(GdprRecord.class)))
.via(r -> KV.of(r.getUserId(), r)))
.apply("Window", Window.<KV<String, GdprRecord>>into(
CalendarWindows.days(1, "Europe/Paris"))
.triggering(AfterWatermark.pastEndOfWindow()
.withEarlyFirings(AfterProcessingTime.pastFirstElementInPane()
.plusDelayOf(Duration.standardMinutes(30))))
.withAllowedLateness(Duration.ZERO)
.accumulatingFiredPanes());
// 3. 生成合规指标
PCollection<ReportRow> report = bySubject
.apply("CombinePerSubject", Combine.perKey(new GdprAccumulatorFn()))
.apply("ToReportRow", ParDo.of(new ReportRowFn()));
// 4. 写成分片文件
report.apply("WriteAvro", FileIO.<ReportRow>write()
.via(AvroIO.sink(ReportRow.class).withCodec(CodecFactory.snappyCodec()))
.to(opts.getReportRoot() + "gdpr_" + System.currentTimeMillis())
.withNaming(ShardingNaming.of("part-", ".avro"))
.withNumShards(10));
// 5. 转 Markdown 并压缩
PCollection<String> markdown = report
.apply("ToMarkdown", ParDo.of(new MarkdownRendererFn()))
.setCoder(StringUtf8Coder.of());
String zipPath = opts.getReportRoot() + "gdpr_report.zip";
markdown.apply("CreateZip", TextIO.write().to(zipPath).withoutSharding());
// 6. 邮件发送
markdown.apply("SendEmail", ParDo.of(new SmtpSendFn(opts.getKmsResource(), zipPath)));
p.run().waitUntilFinish();
}
}
// 关键函数:PII 标注
static class PiiTaggerFn extends DoFn<Row, GdprRecord> {
@ProcessElement
public void process(@Element Row in, OutputReceiver<GdprRecord> out) {
GdprRecord.Builder b = GdprRecord.newBuilder()
.setUserId(in.getString("user_id"))
.setAction(in.getString("action"));
if (in.getString("email") != null) {
b.setEmail(in.getString("email"))
.addGdprCategory(GdprCategory.EMAIL);
}
if (in.getString("phone") != null) {
b.setPhone(in.getString("phone"))
.addGdprCategory(GdprCategory.PHONE);
}
out.output(b.build());
}
}
// 关键函数:SMTP 发送,附件分片 < 10 MB
static class SmtpSendFn extends DoFn<String, Void> {
private final ValueProvider<String> kmsResource;
private final String zipPath;
SmtpSendFn(ValueProvider<String> kms, String path) {
this.kmsResource = kms; this.zipPath = path;
}
@ProcessElement
public void process() throws Exception {
String pwd = KmsUtil.decrypt(kmsResource.get()); // 国内 KMS 接口
Session s = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("gdpr@company.cn", pwd);
}
});
MimeMessage msg = new MimeMessage(s);
msg.setFrom(new InternetAddress("gdpr@company.cn"));
msg.setRecipients(Message.RecipientType.TO, "dpo@company.cn");
msg.setSubject("GDPR 合规日报 " + LocalDate.now());
MimeBodyPart text = new MimeBodyPart();
text.setText("详见附件,分片大小已按网关要求压缩。");
MimeBodyPart attach = new MimeBodyPart();
attach.attachFile(zipPath);
Multipart mp = new MimeMultipart();
mp.addBodyPart(text); mp.addBodyPart(attach);
msg.setContent(mp);
Transport.send(msg);
}
}
运行命令:
mvn compile exec:java -Dexec.mainClass=GdprCompliancePipeline -Dexec.args="--runner=FlinkRunner --jdbcUrl=secret://mysql-cnn --kmsResource=acs:kms:cn-shanghai:123456:key/abc"
输出结果:
- 阿里云 OSS 目录出现
gdpr_report.zip(< 10 MB) - 邮件到达 dpo@company.cn,正文带 x-opt-acl-audit-id,可回溯到 Beam Metrics
- 整个 Pipeline 在 Dataflow 上重跑无需改一行代码,满足 GDPR 第 30 条“可移植”要求。
拓展思考
- 灰度法规变更:把 GDPR 条款做成Protobuf 枚举存在 GCS,Pipeline 启动时动态拉取,法规微调后只需更新枚举版本即可重跑历史数据,实现配置即代码。
- 跨境传输审计:当数据要回传欧盟节点时,在 ParDo 里调用阿里云跨境数据审计 API,把审批单号写回报告,做到事前阻断、事中留痕、事后追溯。
- Serverless 弹性:国内夜间低峰期,利用Dataflow Prime 的垂直自动伸缩,把 Worker 从 4 核升到 32 核,30 分钟完成亿级记录合规扫描,成本比常驻集群节省 42%。
- 数据主体权利自动化:在 Beam 管道末端再接一个KafkaIO.write,把“删除权”事件推送到业务系统,实现RT < 5 分钟的“被遗忘权”闭环,面试官听到“实时删除”通常会给技术深度加分。