<commit_before>import Ember from 'ember';
import Response from 'ember-cli-mirage/response';
import { HOSTS } from './common';
import { logFrames, logEncode } from './data/logs';
import { generateDiff } from './factories/job-version';

const { copy } = Ember;

export function findLeader(schema) {
  const agent = schema.agents.first();
  return `${agent.address}:${agent.tags.port}`;
}

export default function() {
  this.timing = 0; // delay for each request, automatically set to 0 during testing

  this.namespace = 'v1';
  this.trackRequests = Ember.testing;

  const nomadIndices = {}; // used for tracking blocking queries
  const server = this;
  const withBlockingSupport = function(fn) {
    return function(schema, request) {
      // Get the original response
      let { url } = request;
      url = url.replace(/index=\d+[&;]?/, '');
      const response = fn.apply(this, arguments);

      // Get and increment the appropriate index
      nomadIndices[url] || (nomadIndices[url] = 2);
      const index = nomadIndices[url];
      nomadIndices[url]++;

      // Annotate the response with the index
      if (response instanceof Response) {
        response.headers['X-Nomad-Index'] = index;
        return response;
      }
      return new Response(200, { 'x-nomad-index': index }, response);
    };
  };

  this.get(
    '/jobs',
    withBlockingSupport(function({ jobs }, { queryParams }) {
      const json = this.serialize(jobs.all());
      const namespace = queryParams.namespace || 'default';
      return json
        .filter(
          job =>
            namespace === 'default'
              ? !job.NamespaceID || job.NamespaceID === namespace
              : job.NamespaceID === namespace
        )
        .map(job => filterKeys(job, 'TaskGroups', 'NamespaceID'));
    })
  );

  this.post('/jobs', function({ jobs }, req) {
    const body = JSON.parse(req.requestBody);

    if (!body.Job) return new Response(400, {}, 'Job is a required field on the request payload');

    return okEmpty();
  });

  this.post('/jobs/parse', function({ jobs }, req) {
    const body = JSON.parse(req.requestBody);

    if (!body.JobHCL)
      return new Response(400, {}, 'JobHCL is a required field on the request payload');
    if (!body.Canonicalize) return new Response(400, {}, 'Expected Canonicalize to be true');

    return new Response(200, {}, this.serialize(jobs.first()));
  });

  this.post('/job/:id/plan', function({ jobs }, req) {
    const body = JSON.parse(req.requestBody);

    if (!body.Job) return new Response(400, {}, 'Job is a required field on the request payload');
    if (!body.Diff) return new Response(400, {}, 'Expected Diff to be true');

    return new Response(200, {}, JSON.stringify({ Diff: generateDiff(req.params.id) }));
  });

  this.get(
    '/job/:id',
    withBlockingSupport(function({ jobs }, { params, queryParams }) {
      const job = jobs.all().models.find(job => {
        const jobIsDefault = !job.namespaceId || job.namespaceId === 'default';
        const qpIsDefault = !queryParams.namespace || queryParams.namespace === 'default';
        return (
          job.id === params.id &&
          (job.namespaceId === queryParams.namespace || (jobIsDefault && qpIsDefault))
        );
      });

      return job ? this.serialize(job) : new Response(404, {}, null);
    })
  );

  this.get(<commit_msg>Rework job parse mirage request to get the job ID out of the payload<commit_after>import Ember from 'ember';
import Response from 'ember-cli-mirage/response';
import { HOSTS } from './common';
import { logFrames, logEncode } from './data/logs';
import { generateDiff } from './factories/job-version';

const { copy } = Ember;

export function findLeader(schema) {
  const agent = schema.agents.first();
  return `${agent.address}:${agent.tags.port}`;
}

export default function() {
  this.timing = 0; // delay for each request, automatically set to 0 during testing

  this.namespace = 'v1';
  this.trackRequests = Ember.testing;

  const nomadIndices = {}; // used for tracking blocking queries
  const server = this;
  const withBlockingSupport = function(fn) {
    return function(schema, request) {
      // Get the original response
      let { url } = request;
      url = url.replace(/index=\d+[&;]?/, '');
      const response = fn.apply(this, arguments);

      // Get and increment the appropriate index
      nomadIndices[url] || (nomadIndices[url] = 2);
      const index = nomadIndices[url];
      nomadIndices[url]++;

      // Annotate the response with the index
      if (response instanceof Response) {
        response.headers['X-Nomad-Index'] = index;
        return response;
      }
      return new Response(200, { 'x-nomad-index': index }, response);
    };
  };

  this.get(
    '/jobs',
    withBlockingSupport(function({ jobs }, { queryParams }) {
      const json = this.serialize(jobs.all());
      const namespace = queryParams.namespace || 'default';
      return json
        .filter(
          job =>
            namespace === 'default'
              ? !job.NamespaceID || job.NamespaceID === namespace
              : job.NamespaceID === namespace
        )
        .map(job => filterKeys(job, 'TaskGroups', 'NamespaceID'));
    })
  );

  this.post('/jobs', function({ jobs }, req) {
    const body = JSON.parse(req.requestBody);

    if (!body.Job) return new Response(400, {}, 'Job is a required field on the request payload');

    return okEmpty();
  });

  this.post('/jobs/parse', function({ jobs }, req) {
    const body = JSON.parse(req.requestBody);

    if (!body.JobHCL)
      return new Response(400, {}, 'JobHCL is a required field on the request payload');
    if (!body.Canonicalize) return new Response(400, {}, 'Expected Canonicalize to be true');

    // Parse the name out of the first real line of HCL to match IDs in the new job record
    // Regex expectation:
    //   in:  job "job-name" {
    //   out: job-name
    const nameFromHCLBlock = /.+?"(.+?)"/;
    const jobName = body.JobHCL.trim()
      .split('\n')[0]
      .match(nameFromHCLBlock)[1];

    const job = server.create('job', { id: jobName });
    return new Response(200, {}, this.serialize(job));
  });

  this.post('/job/:id/plan', function({ jobs }, req) {
    const body = JSON.parse(req.requestBody);

    if (!body.Job) return new Response(400, {}, 'Job is a required field on the request payload');
    if (!body.Diff) return new Response(400, {}, 'Expected Diff to be true');

    return new Response(200, {}, JSON.stringify({ Diff: generateDiff(req.params.id) }));
  });

  this.get(
    '/job/:id',
    withBlockingSupport(function({ jobs }, { params, queryParams }) {
      const job = jobs.all().models.find(job => {
        const jobIsDefault = !job.namespaceId || job.namespaceId === 'default';
        const qpIsDefault = !queryParams.namespace || queryParams.namespace === 'default';
        return (
          job.id === params.id &&
          (job.namespaceId === queryParams.namespace || (jobIsDefault && qpIsDefault))
        );
      });

      return job ? this.serialize(job) : new Response(404, {}, null);
    })
  );

  this.get(
{'fraction_non_alphanumeric': 0.1518756998880179, 'fraction_numerical': 0.008958566629339306, 'mean_word_length': 2.8747288503253796, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5175146', 'n_tokens_mistral': 2145, 'n_tokens_neox': 2070, 'n_words': 586}