Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Firebase Cloud Functions: New opportunities of serverless backend

GDG SPb
September 30, 2017

Firebase Cloud Functions: New opportunities of serverless backend

Думаете, что отлично знакомы с Firebase Cloud Functions? Тогда будьте готовы удивляться. Александр Денисов расскажет не только о классической работе с Cloud Functions, но и о их взаимодействии с множеством других инструментов и ресурсов.

GDG SPb

September 30, 2017
Tweet

More Decks by GDG SPb

Other Decks in Programming

Transcript

  1. Firebase Cloud Functions: New opportunities of serverless backend. Aleksandr Denisov

    @shuregdenisov Lead Software Engineer- NetCracker. Organizer - GDG Nizhny Novgorod
  2. - Overview of Google Cloud Functions - Review of new

    Firebase features - Using Cloud Functions for Firebase for extending the backend capabilities, examples - Example of using Google Assistent, API.AI with Cloud Functions for Firebase - Dynamic hosting on Firebase using Cloud Functions - Cloud Functions or AWS Lambda. Advantages and disadvantages Agenda:
  3. • HTTP • Cloud Storage • Cloud Pub/Sub • Stackdriver

    Logging • Firebase (DB, Storage, Analytics, Auth)
  4. • Realtime Database Triggers : onWrite, onCreate, onUpdate, onDelete •

    Authentication Triggers: onCreate, onDelete • Cloud Storage Triggers: onChange • Analytics Triggers: onLog • Cloud Pub/Sub Triggers: onPublic • HTTP Triggers: onRequest
  5. Preparation: 1. Create a Firebase project 2. Install the Firebase

    Command Line Interface 3. Connect to the project using Firebase CLI npm -g install firebase-tools firebase login firebase init functions functions/index.js npm install firebase deploy --only functions
  6. exports.addWelcomeMessages = functions.auth.user().onCreate(event => { const user = event.data; console.log('A

    new user signed in for the first time.'); const fullName = user.displayName || 'Anonymous'; // В базу данных будет положено сообщение от файрбез бота о добавлении нового пользователя return admin.database().ref('messages').push({ name: 'Firebase Bot', photoUrl: 'https://image.ibb.co/b7A7Sa/firebase_logo.png', // Firebase logo выгружен на первый попавшийся image hosting text: '${fullName} signed in for the first time! Welcome!' }); });
  7. exports.assistantcodelab = functions.https.onRequest((request, response) => { console.log('headers: ' + JSON.stringify(request.headers));

    console.log('body: ' + JSON.stringify(request.body)); const assistant = new Assistant({request: request, response: response}); let actionMap = new Map(); actionMap.set(PLAY_INTENT, play); actionMap.set(NO_INTENT, discriminate); actionMap.set(YES_INTENT, discriminate); actionMap.set(GIVEUP_INTENT, giveUp); actionMap.set(LEARN_THING_INTENT, learnThing); actionMap.set(LEARN_DISCRIM_INTENT, learnDiscrimination); assistant.handleRequest(actionMap); function play(assistant) { console.log('play'); const first_ref = know.child('first'); first_ref.once('value', snap => { const first = snap.val(); console.log(`First: ${first}`); graph.child(first).once('value', snap => { const speech = `<speak> Great! Think of an animal, but don't tell me what it is yet. <break time="3"/> Okay, my first question is: ${snap.val().q}
  8. "hosting": { "public": "public", // Add the following rewrites section

    *within* "hosting" "rewrites": [ { {"source": "/function/**", "function":"myFunction"} } ] } https://<your-project-id>.firebaseapp.com/myFunction firebase.json exports.myFunction = functions.https.onRequest((req, res) => {...});
  9. • Serve dynamic content. • Prerendering for single page apps

    to improve SEO. • Keep your web app lightweight. Examples of dynamic generation of content
  10. VS.

  11. Functionality AWS Lambda Cloud Functions Scalability & availability Automatic scaling

    (transparent) Automatic scaling Max. # of functions Unlimited functions 1000 functions per project Concurrent executions 1000 parallel executions per account per region 1000 parallel executions (per function) Max deployment size 50 Mb (250 unzipped) 100 Mb (500 unzipped) Max. execution time 300 seconds (5 minutes) 540 seconds (9 minutes) Supported Languages JavaScript, Java, C# and Python Only Javascript Dependencies Deployment Packages npm package.json Logging CloudWatch Logs Stackdriver Logging Event-driven Event Sources (S3, SNS, SES, DynamoDB, Kinesis, CloudWatch) Cloud Pub/Sub or Cloud Storage Object Change Notifications, Firebase events
  12. Invocations per Month Price/Million First 2 million Free Beyond 2

    million $0.40 Type Price/GB Outbound Data (Egress) $0.12 Outbound Data per month 5GB Free Inbound Data (Ingress) Free Outbound Data to Google APIs in the same region Free Unit Price GB-Second $0.0000025 GHz-Second $0.0000100 Compute time Invocations Networking Pricing
  13. Metric Gross Value Free Tier Net Value Unit Price Total

    Price Invocations 10,000,000 2,000,000 8,000,000 $0.0000004 $3.20 GB-seconds 375,000 400,000 < 0 $0.0000025 $0.00 GHz-seconds 600,000 200,000 400,000 $0.0000100 $4.00 Networking 0 5 0 $0.12 $0.00 Total / Month $7.20 Metric Gross Value Free Tier Net Value Unit Price Total Price Invocations 10,000,000 1,000,000 9,000,000 $0.0000002 $1.80 GB-seconds 375,000 400,000 < 0 $0.00001667 $0.00 Total / Month $1.80
  14. Metric Gross Value Free Tier Net Value Unit Price Total

    Price Invocations 50,000,000 2,000,000 48,000,000 $0.0000004 $19.20 GB-seconds 6,250,000 400,000 5,850,000 $0.0000025 $14.63 GHz-seconds 10,000,000 200,000 9,800,000 $0.0000100 $98.00 Networking 232.42 5 233.42 $0.12 $28.01 Total / Month $159.04 Metric Gross Value Free Tier Net Value Unit Price Total Price Invocations 50,000,000 1,000,000 49,000,000 $0.0000002 $9.80 GB-seconds 6,250,000 400,000 5,850,000 $0.00001667 $97.52 Total / Month $107.32