Lambda

  • 서버리스 컴퓨팅

  • Amazon API Gateway를 통한 HTTP 요청, Amazon Simple Storage Service(Amazon S3) 버킷에 있는 객체에 대한 변경 사항, Amazon DynamoDB의 테이블 업데이트, AWS Step Functions의 상태 전화과 같은 다양한 이벤트에 대한 응답으로 코드를 자동 실행할 수 있음

AWS를 활용하여 Slack Bot 연동하기

  • Slack Bot 생성하기

  • Slack Event를 전달 받을 URL 생성하기: AWS API Gateway

    • 신규 생성한 AWS API Gateway의 URL을 Slack 'Features > Event Subscriptions' 설정의 'Request URL’에 등록한다.

    • 이 때, 인증 실페 관련된 오류를 볼 수 있는데 이는 이벤트를 처리할 서버에서 추가 작업이 필요하다.

  • Slack Event를 처리할 서버 생성하기: AWS Lambda

    • 특정 람다 함수를 실행시키는 트리거는 AWS API Gateway를 활용할 수 있다.

    • 인증 실패 관련 오류를 처리할 예시 코드는 아래와 같다.

      const VERIFICATION_TOKEN = "<Verfication Token>" // (1)
      
      const response = (statusCode, body) => {
          return {
              statusCode: statusCode,
              body: body
          }
      }
      
      // Lambda handler
      exports.handler = async (event, context) => {
          // init logging
          console.log("event", event)
      
          // // Verify Url - https://api.slack.com/events/url_verification
          if(
              event.httpMethod === "POST" &&
              event.resource === "/<resource>" && // (2)
              !!event.body
          ) {
              const data = JSON.parse(event.body)
      
              if (data.token === VERIFICATION_TOKEN) {
                  return response(200, JSON.stringify({ "challenge": data.challenge }));
              } else {
                  return response(403, "verification failed");
              }
          }
      
          // custom actions
          return {
              statusCode: 200,
              body: JSON.stringify(
                  {
                      message: "Hello world!"
                  }
              )
          }
      };
      1. Settings > Basic Information > App Credentials > Verification Token

      2. API Gateway의 스테이지 값이 아닌 별도로 지정한 '경로’의 root를 지정한다.

  • Slash Commands에 명령어 하나 추가해서 테스트하기 위한 Lambda Function

    const https = require('https')
    const qs = require('querystring')
    
    const VERIFICATION_TOKEN = "<Verfication Token>"
    
    const response = (statusCode, body) => {
        return {
            statusCode: statusCode,
            body: body
        }
    }
    
    const getBody = (body, isBase64Encoded) => {
        if(isBase64Encoded) {
            return Buffer.from(body, 'base64').toString(); // (1)
        } else {
            return body
        }
    }
    
    // Lambda handler
    exports.handler = async (event, context) => {
        // init logging
        console.log("event", event)
    
        // // Verify Url - https://api.slack.com/events/url_verification
        if(
            event.httpMethod === "POST" &&
            event.resource === "/slack" &&
            !!event.body
        ) {
            const data = JSON.parse(event.body)
            if (data.token === VERIFICATION_TOKEN) {
                return response(200, JSON.stringify({ "challenge": data.challenge }));
            } else {
                return response(403, "verification failed");
            }
        }
    
        // custom actions
        const body = getBody(event.body, event.isBase64Encoded)
        console.log("request.body", body)
    
        return {
            statusCode: 200,
            body: JSON.stringify(qs.parse(body))
        }
    };
    1. atob 함수를 사용할 수 없어서 다른 방법으로 Base64 디코딩을 한다.

Slack 메시지를 전달하는 방법

Incoming Webhooks

  • Incoming Webhooks - 메시지를 전달하는 가장 쉬운 방법

  • 이 방법으로는 게시된 메시지를 삭제할 수 없음. 좀 더 복잡한 채팅 흐름이 필요하다면 chat.postMessage 사용

API로 전달하기

발송 절차
  1. OAuth Token 확인

    • 'Features > OAuth & Permissions' 탭에서 'OAuth Tokens for Your Workspace’에서 'Bot User OAuth Token' 확인

    • 'Settings > Install App' 탭에서 'OAuth Tokens for Your Workspace’에서 'Bot User OAuth Token' 확인

  2. 채팅 발송 및 채널 조회 권한 추가

    • 'Features > OAuth & Permissions' 탭에서 'Scopes’에서 아래 3개 추가

      • channels:read

      • chat:write

      • chat:write.public

  3. chat.postMessage API를 통해 알림 발송

    채널명을 그대로 사용하는 경우
    curl -d '{"channel": "일반", "text":"Hello World"}' \
    -H "Content-type: application/json" \
    -H "Authorization: Bearer <xoxb-로 시작하는 토큰>" \
    -X POST https://slack.com/api/chat.postMessage
    채널명을 그대로 사용하는 경우
    curl -d '{"channel": "<C로 시작되는 채널 ID>", "text":"Hello World"}' \
    -H "Content-type: application/json" \
    -H "Authorization: Bearer <xoxb-로 시작하는 토큰>" \
    -X POST https://slack.com/api/chat.postMessage

참고

모니터링

  • p90, p95, p99

    • 백분위 수

    • 백분위수(percentile)에는 제1백분위수부터 제99백분위수까지 있다.

    • DD-Sketch

      • VLDB19(데이터베이스 학회)에서 소개된 자료구조

      • 모든 값을 가지고 있지 않아도 P95, p50등과 같은 백분위수를 계산 할 수 있음

      • https://blog.imqa.io/statistical-info/

    • "`p99 1.403` 은 10초간 가장 느린 요청 1%의 평균 지연 시간이 1.403초임을 뜻합니다." (참고)