SlideShare ist ein Scribd-Unternehmen logo
1 von 26
Downloaden Sie, um offline zu lesen
Node.js 與 Google 
Cloud Storage 
多麼痛的領悟
關於我 
• Ian Wu 
• 瘋⼈人院院⻑⾧長 
• 頑⽪皮⼯工坊 Backend Engineer 
• http://blog.ianwu.tw/about-me/
Why google cloud storage 
• 內建 CDN 
• Google Cloud Storage behaves essentially like 
a Content Delivery Network (CDN) with no work on 
your part because publicly readable objects are, by 
default, cached in the Google Cloud Storage network. 
• try try see 
• try 到死 
• 有 USD 500 的 credit
OAuth2 
• JWT (JSON Web Token) 
• Google Cloud console 
• credential: service account 
• covert p12 > pem 
Authentication - Google Cloud Storage — Google Cloud Platform 
https://cloud.google.com/storage/docs/authentication#service_accounts
OAuth2 
• Get token 
• payload 
{ 
iss: '460520686343-k6tfn73sentmh0ss5nu67kniorbcta8n@developer.gserviceaccount.com', 
scope: 'https://www.googleapis.com/auth/devstorage.full_control', 
aud: 'https://accounts.google.com/o/oauth2/token', 
exp: 1418280623, 
iat: 1418280563 
} 
• jwt sign 
// sign with RSA SHA256 
var cert = fs.readFileSync('google_cloud_key.pem'); // get private key 
var claim = jwt.sign(payload, cert, { 
Get Google JWT token. 
https://gist.github.com/onlinemad/28341a343ecde186a410 
algorithm: 'RS256' 
});
OAuth2 
• token 
{ 
access_token: 'ya29.2QA9sZg_YtCTGJf1d6Vzxr_4ypioiaIdHJBmgxq6b1HsJuAPODCHnCvt', 
token_type: 'Bearer', 
expires_in: 3600 
} 
• 使⽤用 token 
headers: { Authorization: 'Bearer ' + token.access_token }
Upload URI 
• Upload URI, for media upload requests 
• upload/storage/v1/b/bucket/o 
• Metadata URI, for metadata-only requests: 
• storage/v1/b/bucket/o 
• APIs Explorer currently supports metadata 
requests only.
Upload method 
• simple 
• 就 post 上傳檔案 
• multipart(推薦使⽤用) 
• 可以連 metadata ⼀一起上傳 
• request 某⼀一個版本以上才有⽀支援 
• resumable 
• 沒⽤用過 
• node-youtube-resumable-upload 
https://github.com/grayleonard/node-youtube-resumable-upload
multipart 
• request 
var url = 'https://www.googleapis.com/upload/storage/v1/b/yourbucket/o?' + 
qs.stringify(querystring); 
request.post({ 
preambleCRLF: true, 
postambleCRLF: true, 
url: url, 
multipart: [ 
{ 'Content-Type': 'application/json', body: JSON.stringify(metadata) }, 
{ body: __newFile } 
], 
headers: { Authorization: 'Bearer ' + token.access_token } 
});
multipart 
• body 
{ 
cacheControl: 'public, max-age=604800', 
acl: [{ 
entity: 'allUsers', 
role: 'READER' 
}, { 
entity: 'project-owners-692227494718', 
role: 'OWNER' 
}] 
} 
• query string 
• 不能跟 Request body ⼀一起⽤用
Directory structure 
• ⼀一切都是平的 
• 跟 s3 ⼀一樣 
• 所以沒有建⽴立 folder 這件事情 
• name = foo/bar.jpg;
Directory structure 
• simple 
• /o?name=foo%2Fbar.jpg 
• multipart 
• body.name = foo/bar.jpg
Access URL 
• Standard(推薦) 
• storage.googleapis.com/<bucket>/<object> 
• <bucket>.storage.googleapis.com/<object> 
• CNAME 
• travel-maps.example.com CNAME c.storage.googleapis.com 
• no ssl 
• Cookie-based Authentication 
• 沒⽤用過
Versioning 
• 預設是關掉的 
➜ ~ gsutil versioning get gs://onlinemad-versioning 
gs://onlinemad-versioning: Suspended 
➜ ~ gsutil versioning set on gs://onlinemad-versioning 
Enabling versioning for gs://onlinemad-versioning/... 
➜ ~ 
• qs + generation 
{ 
"kind": "storage#object", 
"id": "onlinemad-dev/uploaded.jpg/1418291876469000", 
"selfLink": "https://www.googleapis.com/storage/v1/b/onlinemad-dev/o/uploaded.jpg", 
"name": "uploaded.jpg", 
"bucket": "onlinemad-dev", 
"generation": "1418291876469000", 
"metageneration": "1", 
"contentType": "image/jpeg", 
"updated": “2014-12-11T09:57:56.468Z”, 
}
ACL 
[ 
{ 
"entity": "project-owners-460520686343", 
"projectTeam": { 
"projectNumber": "460520686343", 
"team": "owners" 
}, 
"role": "OWNER" 
}, 
{ 
"entity": "project-editors-460520686343", 
"projectTeam": { 
"projectNumber": "460520686343", 
"team": "editors" 
}, 
"role": "OWNER" 
}, 
{ 
"entity": "project-viewers-460520686343", 
"projectTeam": { 
"projectNumber": "460520686343", 
"team": "viewers" 
}, 
"role": "READER" 
}, 
{ 
"entity": "user-00b4903a9745459d3abf193213c0f30d5dea50ee7e3e318007a7edfaecb646e5", 
"entityId": "00b4903a9745459d3abf193213c0f30d5dea50ee7e3e318007a7edfaecb646e5", 
"role": "OWNER" 
} 
]
ACL 
• 我需要 public read 
• 所以request.post({ 
preambleCRLF: true, 
postambleCRLF: true, 
url: url, 
multipart: [{ 
'Content-Type': 'application/json', 
body: JSON.stringify({ 
name: 'acl_multipart_upload_public_read.jpg', 
acl: [{ 
entity: 'allUsers', 
role: 'READER' 
}] 
}) 
}, { 
body: data 
}], 
headers: { 
Authorization: 'Bearer ' + token.access_token 
} 
})
ACL 
➜ ~ gsutil acl get gs://onlinemad-dev/ 
acl_simple_upload_public_read.jpg 
AccessDeniedException: Access denied. Please ensure you 
have OWNER permission on gs://onlinemad-dev/ 
acl_simple_upload_public_read.jpg.
這是 feature 不是 bug 
這是 feature 不是 bug 
這是 feature 不是 bug
ACL
ACL 
request.post({ 
preambleCRLF: true, 
postambleCRLF: true, 
url: url, 
multipart: [{ 
'Content-Type': 'application/json', 
body: JSON.stringify({ 
name: 'acl_multipart_upload_public_read_add_owner.jpg', 
acl: [{ 
entity: 'allUsers', 
role: 'READER' 
}, { 
entity: 'project-owners-460520686343', 
role: 'OWNER' 
}] 
}) 
}, { 
body: data 
}], 
headers: { 
Authorization: 'Bearer ' + token.access_token 
} 
})
我的領悟
「還沒有⼈人分享 Google Service 時, 
請勿輕易嘗試」 
– Ian Wu
「當你試了 Google Service 時, 
請來分享」 
– Ian Wu
謝謝⼤大家

Weitere ähnliche Inhalte

Was ist angesagt?

Firebase_not_really_yohoho
Firebase_not_really_yohohoFirebase_not_really_yohoho
Firebase_not_really_yohoho
Roman Sachenko
 
Apache CouchDB talk at Ontario GNU Linux Fest
Apache CouchDB talk at Ontario GNU Linux FestApache CouchDB talk at Ontario GNU Linux Fest
Apache CouchDB talk at Ontario GNU Linux Fest
Myles Braithwaite
 
Security and performance designs for client-server communications
Security and performance designs for client-server communicationsSecurity and performance designs for client-server communications
Security and performance designs for client-server communications
WO Community
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
MongoDB
 
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
mfrancis
 
高性能かつスケールアウト可能なHPCクラウド AIST Super Green Cloud
高性能かつスケールアウト可能なHPCクラウド AIST Super Green Cloud高性能かつスケールアウト可能なHPCクラウド AIST Super Green Cloud
高性能かつスケールアウト可能なHPCクラウド AIST Super Green Cloud
Ryousei Takano
 
Building Your First Application with MongoDB
Building Your First Application with MongoDBBuilding Your First Application with MongoDB
Building Your First Application with MongoDB
MongoDB
 
Gazelle - Plack Handler for performance freaks #yokohamapm
Gazelle - Plack Handler for performance freaks #yokohamapmGazelle - Plack Handler for performance freaks #yokohamapm
Gazelle - Plack Handler for performance freaks #yokohamapm
Masahiro Nagano
 

Was ist angesagt? (20)

Firebase_not_really_yohoho
Firebase_not_really_yohohoFirebase_not_really_yohoho
Firebase_not_really_yohoho
 
Getting started with DataStax .NET Driver for Cassandra
Getting started with DataStax .NET Driver for CassandraGetting started with DataStax .NET Driver for Cassandra
Getting started with DataStax .NET Driver for Cassandra
 
Ecom2
Ecom2Ecom2
Ecom2
 
Back to Basics: My First MongoDB Application
Back to Basics: My First MongoDB ApplicationBack to Basics: My First MongoDB Application
Back to Basics: My First MongoDB Application
 
Streaming using Kafka Flink & Elasticsearch
Streaming using Kafka Flink & ElasticsearchStreaming using Kafka Flink & Elasticsearch
Streaming using Kafka Flink & Elasticsearch
 
Apache CouchDB talk at Ontario GNU Linux Fest
Apache CouchDB talk at Ontario GNU Linux FestApache CouchDB talk at Ontario GNU Linux Fest
Apache CouchDB talk at Ontario GNU Linux Fest
 
Resource registries plone conf 2014
Resource registries plone conf 2014Resource registries plone conf 2014
Resource registries plone conf 2014
 
Connect Intergration Patterns: A Case Study - Patrick Streule
Connect Intergration Patterns: A Case Study - Patrick StreuleConnect Intergration Patterns: A Case Study - Patrick Streule
Connect Intergration Patterns: A Case Study - Patrick Streule
 
Design & Performance - Steve Souders at Fastly Altitude 2015
Design & Performance - Steve Souders at Fastly Altitude 2015Design & Performance - Steve Souders at Fastly Altitude 2015
Design & Performance - Steve Souders at Fastly Altitude 2015
 
Security and performance designs for client-server communications
Security and performance designs for client-server communicationsSecurity and performance designs for client-server communications
Security and performance designs for client-server communications
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
 
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
 
Capture, record, clip, embed and play, search: video from newbie to ninja
Capture, record, clip, embed and play, search: video from newbie to ninjaCapture, record, clip, embed and play, search: video from newbie to ninja
Capture, record, clip, embed and play, search: video from newbie to ninja
 
Working with Cookies in NodeJS
Working with Cookies in NodeJSWorking with Cookies in NodeJS
Working with Cookies in NodeJS
 
高性能かつスケールアウト可能なHPCクラウド AIST Super Green Cloud
高性能かつスケールアウト可能なHPCクラウド AIST Super Green Cloud高性能かつスケールアウト可能なHPCクラウド AIST Super Green Cloud
高性能かつスケールアウト可能なHPCクラウド AIST Super Green Cloud
 
Mobile App Performance: Getting the Most from APIs (MBL203) | AWS re:Invent ...
Mobile App Performance:  Getting the Most from APIs (MBL203) | AWS re:Invent ...Mobile App Performance:  Getting the Most from APIs (MBL203) | AWS re:Invent ...
Mobile App Performance: Getting the Most from APIs (MBL203) | AWS re:Invent ...
 
Building Your First Application with MongoDB
Building Your First Application with MongoDBBuilding Your First Application with MongoDB
Building Your First Application with MongoDB
 
Gazelle - Plack Handler for performance freaks #yokohamapm
Gazelle - Plack Handler for performance freaks #yokohamapmGazelle - Plack Handler for performance freaks #yokohamapm
Gazelle - Plack Handler for performance freaks #yokohamapm
 
JSON Web Tokens (JWT)
JSON Web Tokens (JWT)JSON Web Tokens (JWT)
JSON Web Tokens (JWT)
 
Making web stack tasty using Cloudformation
Making web stack tasty using CloudformationMaking web stack tasty using Cloudformation
Making web stack tasty using Cloudformation
 

Ähnlich wie Node.js 與 google cloud storage

Nk API - examples
Nk API - examplesNk API - examples
Nk API - examples
nasza-klasa
 
Simple blog wall creation on Java
Simple blog wall creation on JavaSimple blog wall creation on Java
Simple blog wall creation on Java
Max Titov
 
2020-02-20 - HashiTalks 2020 - HashiCorp Vault configuration as code via Hash...
2020-02-20 - HashiTalks 2020 - HashiCorp Vault configuration as code via Hash...2020-02-20 - HashiTalks 2020 - HashiCorp Vault configuration as code via Hash...
2020-02-20 - HashiTalks 2020 - HashiCorp Vault configuration as code via Hash...
Andrey Devyatkin
 

Ähnlich wie Node.js 與 google cloud storage (20)

Working with Globus Platform Services and Portals
Working with Globus Platform Services and PortalsWorking with Globus Platform Services and Portals
Working with Globus Platform Services and Portals
 
Nk API - examples
Nk API - examplesNk API - examples
Nk API - examples
 
Web Standards Support in WebKit
Web Standards Support in WebKitWeb Standards Support in WebKit
Web Standards Support in WebKit
 
Simple blog wall creation on Java
Simple blog wall creation on JavaSimple blog wall creation on Java
Simple blog wall creation on Java
 
REST
RESTREST
REST
 
Back to Basics Webinar 2 - Your First MongoDB Application
Back to  Basics Webinar 2 - Your First MongoDB ApplicationBack to  Basics Webinar 2 - Your First MongoDB Application
Back to Basics Webinar 2 - Your First MongoDB Application
 
Back to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB ApplicationBack to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB Application
 
2016 pycontw web api authentication
2016 pycontw web api authentication 2016 pycontw web api authentication
2016 pycontw web api authentication
 
2020-02-20 - HashiTalks 2020 - HashiCorp Vault configuration as code via Hash...
2020-02-20 - HashiTalks 2020 - HashiCorp Vault configuration as code via Hash...2020-02-20 - HashiTalks 2020 - HashiCorp Vault configuration as code via Hash...
2020-02-20 - HashiTalks 2020 - HashiCorp Vault configuration as code via Hash...
 
Conceptos básicos. Seminario web 2: Su primera aplicación MongoDB
 Conceptos básicos. Seminario web 2: Su primera aplicación MongoDB Conceptos básicos. Seminario web 2: Su primera aplicación MongoDB
Conceptos básicos. Seminario web 2: Su primera aplicación MongoDB
 
Iac d.damyanov 4.pptx
Iac d.damyanov 4.pptxIac d.damyanov 4.pptx
Iac d.damyanov 4.pptx
 
CloudStack S3
CloudStack S3CloudStack S3
CloudStack S3
 
HashiConf Digital 2020: HashiCorp Vault configuration as code via HashiCorp T...
HashiConf Digital 2020: HashiCorp Vault configuration as code via HashiCorp T...HashiConf Digital 2020: HashiCorp Vault configuration as code via HashiCorp T...
HashiConf Digital 2020: HashiCorp Vault configuration as code via HashiCorp T...
 
Docker & Azure
Docker & AzureDocker & Azure
Docker & Azure
 
Elastic Search
Elastic SearchElastic Search
Elastic Search
 
OSGi and Spring Data for simple (Web) Application Development
OSGi and Spring Data  for simple (Web) Application DevelopmentOSGi and Spring Data  for simple (Web) Application Development
OSGi and Spring Data for simple (Web) Application Development
 
how to use openstack api
how to use openstack apihow to use openstack api
how to use openstack api
 
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
 
Resource Registries: Plone Conference 2014
Resource Registries: Plone Conference 2014Resource Registries: Plone Conference 2014
Resource Registries: Plone Conference 2014
 
Specification-Driven Development of REST APIs by Alexander Zinchuk
Specification-Driven Development of REST APIs by Alexander Zinchuk   Specification-Driven Development of REST APIs by Alexander Zinchuk
Specification-Driven Development of REST APIs by Alexander Zinchuk
 

Kürzlich hochgeladen

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Kürzlich hochgeladen (20)

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 

Node.js 與 google cloud storage

  • 1. Node.js 與 Google Cloud Storage 多麼痛的領悟
  • 2. 關於我 • Ian Wu • 瘋⼈人院院⻑⾧長 • 頑⽪皮⼯工坊 Backend Engineer • http://blog.ianwu.tw/about-me/
  • 3. Why google cloud storage • 內建 CDN • Google Cloud Storage behaves essentially like a Content Delivery Network (CDN) with no work on your part because publicly readable objects are, by default, cached in the Google Cloud Storage network. • try try see • try 到死 • 有 USD 500 的 credit
  • 4. OAuth2 • JWT (JSON Web Token) • Google Cloud console • credential: service account • covert p12 > pem Authentication - Google Cloud Storage — Google Cloud Platform https://cloud.google.com/storage/docs/authentication#service_accounts
  • 5. OAuth2 • Get token • payload { iss: '460520686343-k6tfn73sentmh0ss5nu67kniorbcta8n@developer.gserviceaccount.com', scope: 'https://www.googleapis.com/auth/devstorage.full_control', aud: 'https://accounts.google.com/o/oauth2/token', exp: 1418280623, iat: 1418280563 } • jwt sign // sign with RSA SHA256 var cert = fs.readFileSync('google_cloud_key.pem'); // get private key var claim = jwt.sign(payload, cert, { Get Google JWT token. https://gist.github.com/onlinemad/28341a343ecde186a410 algorithm: 'RS256' });
  • 6. OAuth2 • token { access_token: 'ya29.2QA9sZg_YtCTGJf1d6Vzxr_4ypioiaIdHJBmgxq6b1HsJuAPODCHnCvt', token_type: 'Bearer', expires_in: 3600 } • 使⽤用 token headers: { Authorization: 'Bearer ' + token.access_token }
  • 7. Upload URI • Upload URI, for media upload requests • upload/storage/v1/b/bucket/o • Metadata URI, for metadata-only requests: • storage/v1/b/bucket/o • APIs Explorer currently supports metadata requests only.
  • 8. Upload method • simple • 就 post 上傳檔案 • multipart(推薦使⽤用) • 可以連 metadata ⼀一起上傳 • request 某⼀一個版本以上才有⽀支援 • resumable • 沒⽤用過 • node-youtube-resumable-upload https://github.com/grayleonard/node-youtube-resumable-upload
  • 9. multipart • request var url = 'https://www.googleapis.com/upload/storage/v1/b/yourbucket/o?' + qs.stringify(querystring); request.post({ preambleCRLF: true, postambleCRLF: true, url: url, multipart: [ { 'Content-Type': 'application/json', body: JSON.stringify(metadata) }, { body: __newFile } ], headers: { Authorization: 'Bearer ' + token.access_token } });
  • 10. multipart • body { cacheControl: 'public, max-age=604800', acl: [{ entity: 'allUsers', role: 'READER' }, { entity: 'project-owners-692227494718', role: 'OWNER' }] } • query string • 不能跟 Request body ⼀一起⽤用
  • 11. Directory structure • ⼀一切都是平的 • 跟 s3 ⼀一樣 • 所以沒有建⽴立 folder 這件事情 • name = foo/bar.jpg;
  • 12. Directory structure • simple • /o?name=foo%2Fbar.jpg • multipart • body.name = foo/bar.jpg
  • 13. Access URL • Standard(推薦) • storage.googleapis.com/<bucket>/<object> • <bucket>.storage.googleapis.com/<object> • CNAME • travel-maps.example.com CNAME c.storage.googleapis.com • no ssl • Cookie-based Authentication • 沒⽤用過
  • 14. Versioning • 預設是關掉的 ➜ ~ gsutil versioning get gs://onlinemad-versioning gs://onlinemad-versioning: Suspended ➜ ~ gsutil versioning set on gs://onlinemad-versioning Enabling versioning for gs://onlinemad-versioning/... ➜ ~ • qs + generation { "kind": "storage#object", "id": "onlinemad-dev/uploaded.jpg/1418291876469000", "selfLink": "https://www.googleapis.com/storage/v1/b/onlinemad-dev/o/uploaded.jpg", "name": "uploaded.jpg", "bucket": "onlinemad-dev", "generation": "1418291876469000", "metageneration": "1", "contentType": "image/jpeg", "updated": “2014-12-11T09:57:56.468Z”, }
  • 15. ACL [ { "entity": "project-owners-460520686343", "projectTeam": { "projectNumber": "460520686343", "team": "owners" }, "role": "OWNER" }, { "entity": "project-editors-460520686343", "projectTeam": { "projectNumber": "460520686343", "team": "editors" }, "role": "OWNER" }, { "entity": "project-viewers-460520686343", "projectTeam": { "projectNumber": "460520686343", "team": "viewers" }, "role": "READER" }, { "entity": "user-00b4903a9745459d3abf193213c0f30d5dea50ee7e3e318007a7edfaecb646e5", "entityId": "00b4903a9745459d3abf193213c0f30d5dea50ee7e3e318007a7edfaecb646e5", "role": "OWNER" } ]
  • 16. ACL • 我需要 public read • 所以request.post({ preambleCRLF: true, postambleCRLF: true, url: url, multipart: [{ 'Content-Type': 'application/json', body: JSON.stringify({ name: 'acl_multipart_upload_public_read.jpg', acl: [{ entity: 'allUsers', role: 'READER' }] }) }, { body: data }], headers: { Authorization: 'Bearer ' + token.access_token } })
  • 17. ACL ➜ ~ gsutil acl get gs://onlinemad-dev/ acl_simple_upload_public_read.jpg AccessDeniedException: Access denied. Please ensure you have OWNER permission on gs://onlinemad-dev/ acl_simple_upload_public_read.jpg.
  • 18.
  • 19. 這是 feature 不是 bug 這是 feature 不是 bug 這是 feature 不是 bug
  • 20. ACL
  • 21.
  • 22. ACL request.post({ preambleCRLF: true, postambleCRLF: true, url: url, multipart: [{ 'Content-Type': 'application/json', body: JSON.stringify({ name: 'acl_multipart_upload_public_read_add_owner.jpg', acl: [{ entity: 'allUsers', role: 'READER' }, { entity: 'project-owners-460520686343', role: 'OWNER' }] }) }, { body: data }], headers: { Authorization: 'Bearer ' + token.access_token } })
  • 24. 「還沒有⼈人分享 Google Service 時, 請勿輕易嘗試」 – Ian Wu
  • 25. 「當你試了 Google Service 時, 請來分享」 – Ian Wu