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

CodeFest 2018. Александр Денисов (NetCracker) — Firebase Cloud Functions. Облачный event-driven бэкенд без лишних сложностей

16b6c87229eaf58768d25ed7b2bbbf52?s=47 CodeFest
April 09, 2018

CodeFest 2018. Александр Денисов (NetCracker) — Firebase Cloud Functions. Облачный event-driven бэкенд без лишних сложностей

Посмотрите выступление Александра: https://2018.codefest.ru/lecture/1261/

— Обзор Cloud Functions for Firebase.
— Использование Cloud Functions для создания облачного event-driven бэкенда. Типовые схемы применения. Примеры.
— Firebase CLI (Command Line Interface). Развертывание функций.
— Создание приложения для Google Assistant с помощью Firebase Cloud Functions
— Cloud Functions Shell. Тестируем функции локально.
— Cloud Functions vs AWS Lambda. Плюсы и минусы.

16b6c87229eaf58768d25ed7b2bbbf52?s=128

CodeFest

April 09, 2018
Tweet

Transcript

  1. Firebase Cloud Functions. Облачный event-driven бэкенд без лишних сложностей. Aleksandr

    Denisov @shuregdenisov Lead Software Engineer- NetCracker. Organizer - GDG Nizhny Novgorod
  2. О чем это все будет: • Обзор Cloud Functions for

    Firebase. • Использование Cloud Functions для создания облачного event-driven бэкенда. Типовые схемы применения. Примеры. • Firebase CLI (Command Line Interface). Развертывание функций. • Создание приложения для Google Assistant с помощью Firebase Cloud Functions • Cloud Functions Shell. Тестируем функции локально. • Cloud Functions vs AWS Lambda. Плюсы и минусы.
  3. None
  4. The Evolution of Cloud Services

  5. Google Compute Engine Google Container Engine Google App Engine Google

    Cloud Functions
  6. • HTTP • Cloud Storage • Cloud Pub/Sub • Stackdriver

    Logging • Firebase Realtime Database • Firebase Cloud Firestore • Firebase Authentication • Firebase Cloud Storage • Firebase Analytics • Firebase Crashlytics • HTTP • Cloud Pub/Sub
  7. None
  8. Functions

  9. None
  10. 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!' }); }); const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase);
  11. Firebase CLI (Command Line Interface): 1. Установить Node.js 2. Установить

    Firebase Command Line Interface 3. Подключится к проекту через Firebase CLI npm -g install firebase-tools firebase login firebase init firebase deploy
  12. JavaScript TypeScript

  13. None
  14. • OnCreate • OnDelete Authentication • OnCreate • OnUpdate •

    OnDelete • OnWrite Realtime Database • OnCreate • OnUpdate • OnDelete • OnWrite Cloud Firestore • OnChange Cloud Storage
  15. • OnLog Analytics • OnNewDetected • OnRegressed • OnVelocityAlert Crashlytics

    • OnRequest HTTP • OnPublish Cloud Pub/Sub
  16. None
  17. None
  18. None
  19. None
  20. Привет!

  21. None
  22. ... const ActionsSdkAssistant = require('actions-on-google').ActionsSdkApp; exports.sayNumber = functions.https.onRequest((req, res) =>

    { const assistant = new ActionsSdkAssistant({request: req, response: res}); ... const actionMap = new Map(); ... actionMap.set(assistant.StandardIntents.TEXT, (assistant) => { const rawInput = assistant.getRawInput(); if (rawInput === 'пока') { assistant.tell('Счастливо!'); } else if (isNaN(parseInt(rawInput, 10))) { const inputPrompt = assistant.buildInputPrompt(false, 'Я что-то недопонял число, можешь еще раз сказать?', reprompts); assistant.ask(inputPrompt); } else { const inputPrompt = assistant.buildInputPrompt(true, `<speak> Порядковый номер по числу <say-as interpret-as="cardinal">${rawInput}</say-as> <break time="1"/> <say-as interpret-as="ordinal">${rawInput}</say-as> </speak>`, reprompts ); assistant.ask(inputPrompt); } }); assistant.handleRequest(actionMap); });
  23. Gaction CLI (Command Line Interface): 1. Загрузить gactions.CLI 2. Создать

    action package file action.json 3. Выгрузить action package в проект gactions init gactions update --action_package PACKAGE_NAME --project PROJECT_ID
  24. None
  25. Привет!

  26. А как же тестить? • The Cloud Functions shell. Эмуляция

    всех типов триггеров • The Firebase CLI's firebase serve command. Эмуляция HTTPS firebase experimental:functions:shell firebase serve --only functions firebase serve --only functions,hosting
  27. 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://preview.ibb.co/h6AK4n/hren.gif"', text: 'This is TEST! ${fullName}, hello, dude!' }); }); const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase);
  28. None
  29. None
  30. VS.

  31. 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 Javascript, Typescript 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
  32. None
  33. 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
  34. Spark Plan Generous limits for hobbyists Free Flame Plan Fixed

    pricing for growing apps $25/month Blaze Plan Calculate pricing for apps at scale Pay as you go • Invocations • GB-seconds • CPU-seconds • Outbound networking • 125K/month • 40K/month • 40K/month • Google services only • 2M/month • 400K/month • 200K/month • 5 GB/month • $0.40/million • $0.0025/thousand • $0.01/thousand • $0.12/GB Firebase Pricing
  35. 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
  36. 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
  37. СПАСИБО! docs: https://firebase.google.com/docs/ codelabs: https://codelabs.developers.google.com/codelabs/firebase-android codelabs: https://codelabs.developers.google.com/codelabs/assistant-codelab slack-channel: https://firebase-community.appspot.com/

  38. ВОПРОСЫ?

  39. None