|
| 1 | +// Copyright 2020 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +'use strict'; |
| 16 | + |
| 17 | +// sample-metadata: |
| 18 | +// title: Categorical Risk Analysis |
| 19 | +// description: Computes risk metrics of a column of data in a Google BigQuery table. |
| 20 | +// usage: node categoricalRiskAnalysis.js my-project nhtsa_traffic_fatalities accident_2015 state_name my-topic my-subscription bigquery-public-data |
| 21 | + |
| 22 | +function main( |
| 23 | + projectId, |
| 24 | + tableProjectId, |
| 25 | + datasetId, |
| 26 | + tableId, |
| 27 | + columnName, |
| 28 | + topicId, |
| 29 | + subscriptionId |
| 30 | +) { |
| 31 | + // [START dlp_categorical_stats] |
| 32 | + // Import the Google Cloud client libraries |
| 33 | + const DLP = require('@google-cloud/dlp'); |
| 34 | + const {PubSub} = require('@google-cloud/pubsub'); |
| 35 | + |
| 36 | + // Instantiates clients |
| 37 | + const dlp = new DLP.DlpServiceClient(); |
| 38 | + const pubsub = new PubSub(); |
| 39 | + |
| 40 | + // The project ID to run the API call under |
| 41 | + // const projectId = 'my-project'; |
| 42 | + |
| 43 | + // The project ID the table is stored under |
| 44 | + // This may or (for public datasets) may not equal the calling project ID |
| 45 | + // const tableProjectId = 'my-project'; |
| 46 | + |
| 47 | + // The ID of the dataset to inspect, e.g. 'my_dataset' |
| 48 | + // const datasetId = 'my_dataset'; |
| 49 | + |
| 50 | + // The ID of the table to inspect, e.g. 'my_table' |
| 51 | + // const tableId = 'my_table'; |
| 52 | + |
| 53 | + // The name of the Pub/Sub topic to notify once the job completes |
| 54 | + // TODO(developer): create a Pub/Sub topic to use for this |
| 55 | + // const topicId = 'MY-PUBSUB-TOPIC' |
| 56 | + |
| 57 | + // The name of the Pub/Sub subscription to use when listening for job |
| 58 | + // completion notifications |
| 59 | + // TODO(developer): create a Pub/Sub subscription to use for this |
| 60 | + // const subscriptionId = 'MY-PUBSUB-SUBSCRIPTION' |
| 61 | + |
| 62 | + // The name of the column to compute risk metrics for, e.g. 'firstName' |
| 63 | + // const columnName = 'firstName'; |
| 64 | + async function categoricalRiskAnalysis() { |
| 65 | + const sourceTable = { |
| 66 | + projectId: tableProjectId, |
| 67 | + datasetId: datasetId, |
| 68 | + tableId: tableId, |
| 69 | + }; |
| 70 | + |
| 71 | + // Construct request for creating a risk analysis job |
| 72 | + const request = { |
| 73 | + parent: `projects/${projectId}/locations/global`, |
| 74 | + riskJob: { |
| 75 | + privacyMetric: { |
| 76 | + categoricalStatsConfig: { |
| 77 | + field: { |
| 78 | + name: columnName, |
| 79 | + }, |
| 80 | + }, |
| 81 | + }, |
| 82 | + sourceTable: sourceTable, |
| 83 | + actions: [ |
| 84 | + { |
| 85 | + pubSub: { |
| 86 | + topic: `projects/${projectId}/topics/${topicId}`, |
| 87 | + }, |
| 88 | + }, |
| 89 | + ], |
| 90 | + }, |
| 91 | + }; |
| 92 | + |
| 93 | + // Create helper function for unpacking values |
| 94 | + const getValue = obj => obj[Object.keys(obj)[0]]; |
| 95 | + |
| 96 | + // Run risk analysis job |
| 97 | + const [topicResponse] = await pubsub.topic(topicId).get(); |
| 98 | + const subscription = await topicResponse.subscription(subscriptionId); |
| 99 | + const [jobsResponse] = await dlp.createDlpJob(request); |
| 100 | + const jobName = jobsResponse.name; |
| 101 | + // Watch the Pub/Sub topic until the DLP job finishes |
| 102 | + await new Promise((resolve, reject) => { |
| 103 | + const messageHandler = message => { |
| 104 | + if (message.attributes && message.attributes.DlpJobName === jobName) { |
| 105 | + message.ack(); |
| 106 | + subscription.removeListener('message', messageHandler); |
| 107 | + subscription.removeListener('error', errorHandler); |
| 108 | + resolve(jobName); |
| 109 | + } else { |
| 110 | + message.nack(); |
| 111 | + } |
| 112 | + }; |
| 113 | + |
| 114 | + const errorHandler = err => { |
| 115 | + subscription.removeListener('message', messageHandler); |
| 116 | + subscription.removeListener('error', errorHandler); |
| 117 | + reject(err); |
| 118 | + }; |
| 119 | + |
| 120 | + subscription.on('message', messageHandler); |
| 121 | + subscription.on('error', errorHandler); |
| 122 | + }); |
| 123 | + setTimeout(() => { |
| 124 | + console.log(' Waiting for DLP job to fully complete'); |
| 125 | + }, 500); |
| 126 | + const [job] = await dlp.getDlpJob({name: jobName}); |
| 127 | + const histogramBuckets = |
| 128 | + job.riskDetails.categoricalStatsResult.valueFrequencyHistogramBuckets; |
| 129 | + histogramBuckets.forEach((histogramBucket, histogramBucketIdx) => { |
| 130 | + console.log(`Bucket ${histogramBucketIdx}:`); |
| 131 | + |
| 132 | + // Print bucket stats |
| 133 | + console.log( |
| 134 | + ` Most common value occurs ${histogramBucket.valueFrequencyUpperBound} time(s)` |
| 135 | + ); |
| 136 | + console.log( |
| 137 | + ` Least common value occurs ${histogramBucket.valueFrequencyLowerBound} time(s)` |
| 138 | + ); |
| 139 | + |
| 140 | + // Print bucket values |
| 141 | + console.log(`${histogramBucket.bucketSize} unique values total.`); |
| 142 | + histogramBucket.bucketValues.forEach(valueBucket => { |
| 143 | + console.log( |
| 144 | + ` Value ${getValue(valueBucket.value)} occurs ${ |
| 145 | + valueBucket.count |
| 146 | + } time(s).` |
| 147 | + ); |
| 148 | + }); |
| 149 | + }); |
| 150 | + } |
| 151 | + |
| 152 | + categoricalRiskAnalysis(); |
| 153 | + // [END dlp_categorical_stats] |
| 154 | +} |
| 155 | + |
| 156 | +main(...process.argv.slice(2)); |
| 157 | +process.on('unhandledRejection', err => { |
| 158 | + console.error(err.message); |
| 159 | + process.exitCode = 1; |
| 160 | +}); |
0 commit comments