<commit_before>util = require "util"
fs = require "fs"

restify = require "restify"
yaml = require 'js-yaml'

paths = require "../paths"
Login = require "../Login"
dataHelpers = require "./Helpers"

sandboxDBBaseURL = 'https://datastorage-api.appgyver.com'
sandboxDBURL = "#{sandboxDBBaseURL}/v1/datastorage"

class SandboxDB
  @SandboxDBError: class SandboxDBError extends steroidsCli.SteroidsError
  @ProvisionError: class ProvisionError extends SandboxDBError
  @WriteFileError: class WriteFileError extends SandboxDBError

  providerName: "appgyver_sandbox"
  providerTypeId: 6

  constructor: (@options={}) ->
    @apiClient = restify.createJsonClient
      url: sandboxDBBaseURL
    @apiClient.basicAuth Login.currentAccessToken(), 'X'

  get: =>
    return new Promise (resolve, reject) =>
      steroidsCli.debug "SANDBOXDB", "Initializing Sandbox DB"

      @readFromFile().then =>
        if @existsSync() #TODO: cannot be called before @readFromFile is resolved
          steroidsCli.debug "SANDBOXDB", "Sandbox DB already created"
          resolve()
        else
          steroidsCli.debug "SANDBOXDB", "Sandbox DB not created, creating a new one."
          @create().then resolve

  create: =>
    return new Promise (resolve, reject) =>
      steroidsCli.debug "SANDBOXDB", "Creating Sandbox DB"

      @provision()
      .then(@writeToFile)
      .then(resolve)

  provision: =>
    return new Promise (resolve, reject) =>
      steroidsCli.debug "SANDBOXDB", "Provisioning Sandbox DB"

      data =
        appId: dataHelpers.getAppId()

      steroidsCli.debug "SANDBOXDB", "POSTing data: #{JSON.stringify(data)} to path: /v1/credentials/provision"
      @apiClient.post '/v1/credentials/provision', { data: data }, (err, req, res, obj) =>
        if obj.code == 201 #TODO: betterify this line
          steroidsCli.debug "SANDBOXDB", "Provisioning Sandbox DB returned success: #{JSON.stringify(obj)}"
          @fromApiSchemaDict(obj.body)
          resolve()
        else
          steroidsCli.debug "SANDBOXDB", "Provisioning Sandbox DB returned failure: #{JSON.stringify(obj)}"
          reject new ProvisionError err

  writeToFile: =>
    return new Promise (resolve, reject) =>
      steroidsCli.debug "SANDBOXDB", "Writing configuration to file #{paths.application.configs.data.sandboxdb}"
      steroidsCli.debug "SANDBOXDB", "Writing configuration: #{JSON.stringify(@toConfigurationDict())}"

      dataHelpers.overwriteYamlConfig(paths.application.configs.data.sandboxdb, @toConfigurationDict())
      .then =>
        steroidsCli.debug "SANDBOXDB", "Writing configuration to file #{paths.application.configs.data.sandboxdb} was success"
        resolve()
      .fail (err)=>
        steroidsCli.debug "SANDBOXDB", "Writing configuration to file #{paths.application.configs.data.sandboxdb} was failure", err
        reject new WriteFileError err

  readFromFile: =>
    return new Promise (resolve, reject) =>
      steroidsCli.debug "SANDBOXDB", "Reading configuration from file #{paths.application.configs.data.sandboxdb}"

      unless fs.existsSync(paths.application.configs.data.sandboxdb)
        steroidsCli.debug "SANDBOXDB", "Configuration file #{paths.application.configs.data.sandboxdb} was missing"
        resolve()
        return

      @fromConfigurationDict yaml.safeLoad(fs.readFileSync(paths.application.configs.data.sandboxdb, 'utf8'))

      resolve()

  configurationKeysForProxy: =>
    bucket_id: @id
    steroids_api_key: @apikey
    bucket_name: @name

  # legacy yaml format abstracted here
  toConfigurationDict: =>
    apikey: @apikey
    bucket: @name
    bucket_id: @id

  # legacy yaml format abstracted here
  fromConfigurationDict: (obj)=>
    @apikey = obj.apikey
    @name = obj.bucket
    @id = obj.bucket_id

  # datastore api schema abstracted here
  fromApiSchemaDict: (obj)=>
    @apikey = "#{obj.login}#{obj.password}"
    @name = obj.name
    @id = obj.datastore_bucket_id

  existsSync: -> #TODO: make async
    return @id?

module.exports = SandboxDB
<commit_msg>changed SandboxDB human readable name<commit_after>util = require "util"
fs = require "fs"

restify = require "restify"
yaml = require 'js-yaml'

paths = require "../paths"
Login = require "../Login"
dataHelpers = require "./Helpers"

sandboxDBBaseURL = 'https://datastorage-api.appgyver.com'
sandboxDBURL = "#{sandboxDBBaseURL}/v1/datastorage"

class SandboxDB
  @SandboxDBError: class SandboxDBError extends steroidsCli.SteroidsError
  @ProvisionError: class ProvisionError extends SandboxDBError
  @WriteFileError: class WriteFileError extends SandboxDBError

  providerName: "AppGyver Sandbox Database"
  providerTypeId: 6

  constructor: (@options={}) ->
    @apiClient = restify.createJsonClient
      url: sandboxDBBaseURL
    @apiClient.basicAuth Login.currentAccessToken(), 'X'

  get: =>
    return new Promise (resolve, reject) =>
      steroidsCli.debug "SANDBOXDB", "Initializing Sandbox DB"

      @readFromFile().then =>
        if @existsSync() #TODO: cannot be called before @readFromFile is resolved
          steroidsCli.debug "SANDBOXDB", "Sandbox DB already created"
          resolve()
        else
          steroidsCli.debug "SANDBOXDB", "Sandbox DB not created, creating a new one."
          @create().then resolve

  create: =>
    return new Promise (resolve, reject) =>
      steroidsCli.debug "SANDBOXDB", "Creating Sandbox DB"

      @provision()
      .then(@writeToFile)
      .then(resolve)

  provision: =>
    return new Promise (resolve, reject) =>
      steroidsCli.debug "SANDBOXDB", "Provisioning Sandbox DB"

      data =
        appId: dataHelpers.getAppId()

      steroidsCli.debug "SANDBOXDB", "POSTing data: #{JSON.stringify(data)} to path: /v1/credentials/provision"
      @apiClient.post '/v1/credentials/provision', { data: data }, (err, req, res, obj) =>
        if obj.code == 201 #TODO: betterify this line
          steroidsCli.debug "SANDBOXDB", "Provisioning Sandbox DB returned success: #{JSON.stringify(obj)}"
          @fromApiSchemaDict(obj.body)
          resolve()
        else
          steroidsCli.debug "SANDBOXDB", "Provisioning Sandbox DB returned failure: #{JSON.stringify(obj)}"
          reject new ProvisionError err

  writeToFile: =>
    return new Promise (resolve, reject) =>
      steroidsCli.debug "SANDBOXDB", "Writing configuration to file #{paths.application.configs.data.sandboxdb}"
      steroidsCli.debug "SANDBOXDB", "Writing configuration: #{JSON.stringify(@toConfigurationDict())}"

      dataHelpers.overwriteYamlConfig(paths.application.configs.data.sandboxdb, @toConfigurationDict())
      .then =>
        steroidsCli.debug "SANDBOXDB", "Writing configuration to file #{paths.application.configs.data.sandboxdb} was success"
        resolve()
      .fail (err)=>
        steroidsCli.debug "SANDBOXDB", "Writing configuration to file #{paths.application.configs.data.sandboxdb} was failure", err
        reject new WriteFileError err

  readFromFile: =>
    return new Promise (resolve, reject) =>
      steroidsCli.debug "SANDBOXDB", "Reading configuration from file #{paths.application.configs.data.sandboxdb}"

      unless fs.existsSync(paths.application.configs.data.sandboxdb)
        steroidsCli.debug "SANDBOXDB", "Configuration file #{paths.application.configs.data.sandboxdb} was missing"
        resolve()
        return

      @fromConfigurationDict yaml.safeLoad(fs.readFileSync(paths.application.configs.data.sandboxdb, 'utf8'))

      resolve()

  configurationKeysForProxy: =>
    bucket_id: @id
    steroids_api_key: @apikey
    bucket_name: @name

  # legacy yaml format abstracted here
  toConfigurationDict: =>
    apikey: @apikey
    bucket: @name
    bucket_id: @id

  # legacy yaml format abstracted here
  fromConfigurationDict: (obj)=>
    @apikey = obj.apikey
    @name = obj.bucket
    @id = obj.bucket_id

  # datastore api schema abstracted here
  fromApiSchemaDict: (obj)=>
    @apikey = "#{obj.login}#{obj.password}"
    @name = obj.name
    @id = obj.datastore_bucket_id

  existsSync: -> #TODO: make async
    return @id?

module.exports = SandboxDB

{'fraction_non_alphanumeric': 0.11222098902454064, 'fraction_numerical': 0.001973116290541374, 'mean_word_length': 3.5383324006715164, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 43, 'https://': 2, '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': '4133006', 'n_tokens_mistral': 2600, 'n_tokens_neox': 2428, 'n_words': 606}