All files / src/commands/accesslogs accesslogs.command.js

31.17% Statements 53/170
100% Branches 1/1
0% Functions 0/3
31.17% Lines 53/170

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x                                       193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x                                 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x                                                                                                                                                                     193x 193x  
import { ApplicationAccessLogStream } from '@clevercloud/client/esm/streams/access-logs.js';
import { formatTable } from '../../format-table.js';
import { formatClf } from '../../lib/access-logs-clf.js';
import { defineCommand } from '../../lib/define-command.js';
import { styleText } from '../../lib/style-text.js';
import { Logger } from '../../logger.js';
import * as Application from '../../models/application.js';
import { JsonArray } from '../../models/json-array.js';
import { getHostAndTokens } from '../../models/send-to-api.js';
import { truncateWithEllipsis } from '../../models/utils.js';
import {
  accessLogsFormatOption,
  addonIdOrRealIdOption,
  afterOption,
  aliasOption,
  appIdOrNameOption,
  beforeOption,
} from '../global.options.js';
 
const THROTTLE_ELEMENTS = 2000;
 
const THROTTLE_PER_IN_MILLISECONDS = 100;
 
const CITY_MAX_LENGTH = 20;
 
function formatHuman(log) {
  const { date, http, source } = log;
  const country = source.countryCode ?? '(unknown)';
  const hasSourceCity = source.city ?? '';

  return formatTable(
    [
      [
        styleText('grey', date.toISOString(date)),
        source.ip,
        `${country}${hasSourceCity ? '/' + truncateWithEllipsis(CITY_MAX_LENGTH, source.city) : ''}`,
        colorStatusCode(http.response.statusCode),
        http.request.method.toString().padEnd(4, ' ') + ' ' + http.request.path,
      ],
    ],

    ACCESSLOG_COLUMN_WIDTHS,
  );
}
 
const ACCESSLOG_COLUMN_WIDTHS = [
  '2024-06-24T08:05:43.880Z',
  '255.255.255.255',
  // country / city
  2 + 1 + CITY_MAX_LENGTH,
  'XXX',
  // longest method name
  'OPTIONS',
  // path
];
 
function colorStatusCode(code) {
  const codeString = code.toString();
  if (code >= 500) {
    return styleText('red', codeString);
  }
  if (code >= 400) {
    return styleText('yellow', codeString);
  }
  if (code >= 300) {
    return styleText('blue', codeString);
  }
  if (code >= 200) {
    return styleText('green', codeString);
  }
  return codeString;
}
 
export const accesslogsCommand = defineCommand({
  description: 'Fetch access logs',
  since: '2.1.0',
  options: {
    alias: aliasOption,
    app: appIdOrNameOption,
    format: accessLogsFormatOption,
    before: beforeOption,
    after: afterOption,
    addon: addonIdOrRealIdOption,
  },
  args: [],
  async handler(options) {
    // TODO: drop when add-ons are supported in API
    if (options.addon) {
      throw new Error('Access Logs are not available for add-ons yet');
    }

    const { apiHost, tokens } = await getHostAndTokens();
    const { alias, app: appIdOrName, format, before: until, after: since } = options;
    const { ownerId, appId } = await Application.resolveId(appIdOrName, alias);

    const stream = new ApplicationAccessLogStream({
      apiHost,
      tokens,
      ownerId,
      appId,
      since,
      until,
      throttleElements: THROTTLE_ELEMENTS,
      throttlePerInMilliseconds: THROTTLE_PER_IN_MILLISECONDS,
    });

    if (format === 'human') {
      Logger.println(styleText('yellow', '/!\\ This feature is in Beta testing phase'));
    }

    if (format === 'json' && !until) {
      throw new Error('JSON format only works with a limiting parameter such as `before`');
    }

    // used for 'json' format
    const jsonArray = new JsonArray();

    stream
      .on('open', () => {
        Logger.debug(styleText('blue', `Logs stream (open) ${JSON.stringify({ appId })}`));
        if (format === 'json') {
          jsonArray.open();
        }
      })
      .on('error', (event) => {
        Logger.debug(styleText('red', `Logs stream (error) ${event.error.message}`));
      })
      .onLog((log) => {
        switch (format) {
          case 'json':
            jsonArray.push(log);
            break;
          case 'json-stream':
            Logger.printJson(log);
            break;
          case 'clf':
            // when the connection is cut too early, or for TCP redirections, we don't have HTTP section
            if (log.http == null) {
              break;
            }

            Logger.println(formatClf(log));
            break;
          case 'human':
          default:
            // when the connection is cut too early, or for TCP redirections, we don't have HTTP section
            if (log.http == null) {
              break;
            }

            Logger.println(formatHuman(log));
            break;
        }
      });

    // Properly close the stream
    process.once('SIGINT', (signal) => {
      stream.close(signal);
      process.kill(process.pid, 'SIGINT');
    });

    const closeReason = await stream.start();

    if (format === 'json') {
      jsonArray.close();
    }

    Logger.debug(`stream closed: ${closeReason?.type}`);
  },
});