all repos — litestore @ 3fd542f5f56662801de79b1b7262ee7f333a5977

A minimalist nosql document store.

src/litestore.nim

 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
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
import
  strutils,
  strtabs,
  tables,
  os,
  uri,
  httpcore,
  json
import
  litestorepkg/lib/types,
  litestorepkg/lib/logger,
  litestorepkg/lib/utils,
  litestorepkg/lib/core,
  litestorepkg/lib/cli,
  litestorepkg/lib/server

export
  types,
  server,
  logger,
  utils

from asyncdispatch import runForever

{.compile: "litestorepkg/vendor/sqlite/sqlite3.c".}
{.passC: "-DSQLITE_ENABLE_FTS3=1 -DSQLITE_ENABLE_FTS3_PARENTHESIS -DSQLITE_ENABLE_JSON1".}
when defined(linux):
  {.passL:"-static".}

proc processAuthConfig(configuration: JsonNode, auth: var JsonNode) =
  if auth == newJNull() and configuration != newJNull() and configuration.hasKey("signature"):
    auth = newJObject();
    auth["access"] = newJObject();
    auth["signature"] = configuration["signature"]
    for k, v in configuration["resources"].pairs:
      auth["access"][k] = newJObject()
      for meth, content in v.pairs:
        if content.hasKey("auth"):
          auth["access"][k][meth] = content["auth"]

proc processConfigSettings(LS: var LiteStore) =
  # Process config settings if present and if no cli settings are set
  if LS.config != newJNull() and LS.config.hasKey("settings"):
    let settings = LS.config["settings"]
    let cliSettings = LS.cliSettings
    if not cliSettings.hasKey("address") and settings.hasKey("address"):
      LS.address = settings["address"].getStr
    if not cliSettings.hasKey("port") and settings.hasKey("port"):
      LS.port = settings["port"].getInt
    if not cliSettings.hasKey("store") and settings.hasKey("store"):
      LS.file = settings["store"].getStr
    if not cliSettings.hasKey("directory") and settings.hasKey("directory"):
      LS.directory = settings["directory"].getStr
    if not cliSettings.hasKey("middleware") and settings.hasKey("middleware"):
      let val = settings["middleware"].getStr
      for file in val.walkDir():
        if file.kind == pcFile or file.kind == pcLinkToFile:
          LS.middleware[file.path.splitFile[1]] = file.path.readFile()
    if not cliSettings.hasKey("log") and settings.hasKey("log"):
      LS.logLevel = settings["log"].getStr
      setLogLevel(LS.logLevel)
    if not cliSettings.hasKey("mount") and settings.hasKey("mount"):
      LS.mount = settings["mount"].getBool
    if not cliSettings.hasKey("readonly") and settings.hasKey("readonly"):
      LS.readonly = settings["readonly"].getBool

proc executeOperation*() =
  let file = LS.execution.file
  let body = LS.execution.body
  let ctype = LS.execution.ctype
  let uri = LS.execution.uri
  let operation = LS.execution.operation
  var req:LSRequest
  case operation.toUpperAscii:
    of "GET":
      req.reqMethod = HttpGet
    of "POST":
      req.reqMethod = HttpPost
    of "PUT":
      req.reqMethod = HttpPut
    of "PATCH":
      req.reqMethod = HttpPatch
    of "DELETE":
      req.reqMethod = HttpDelete
    of "OPTIONS":
      req.reqMethod = HttpOptions
    of "HEAD":
      req.reqMethod = HttpHead
    else:
      fail(203, "Operation '$1' is not supported" % [operation])
  if body.len > 0:
    req.body = body
  elif file.len > 0:
    req.body = file.readFile
  req.headers = newHttpHeaders()
  if ctype.len > 0:
    req.headers["Content-Type"] = ctype
  req.hostname = "<cli>"
  req.url = parseUri("$1://$2:$3/$4" % @["http", "localhost", "9500", uri])
  let resp = req.process(LS)
  echo resp.content
  if resp.code.int < 300 and resp.code.int >= 200:
    quit(0)
  else:
    quit(resp.code.int)

proc setup*(LS: var LiteStore, open = true) =
  if not LS.file.fileExists:
    try:
      LOG.debug("Creating datastore: ", LS.file)
      LS.file.createDatastore()
    except:
      eWarn()
      fail(200, "Unable to create datastore '$1'" % [LS.file])
  if (open):
    try:
      LS.store = LS.file.openDatastore()
      try:
        LS.store.upgradeDatastore()
      except:
        fail(203, "Unable to upgrade datastore '$1'" % [LS.file])
      if LS.mount:
        try:
          LS.store.mountDir(LS.directory)
        except:
          eWarn()
          fail(202, "Unable to mount directory '$1'" % [LS.directory])
    except:
      fail(201, "Unable to open datastore '$1'" % [LS.file])

proc initStore(LS: var LiteStore) =
  if LS.configFile == "":
    # Attempt to retrieve config.json from system documents
    let options = newQueryOptions(true)
    let rawDoc = LS.store.retrieveRawDocument("config.json", options)
    if rawDoc != "":
      LS.config = rawDoc.parseJson()["data"]

  if LS.config != newJNull():
    # Process config settings
    LS.processConfigSettings()
    # Process auth from config settings
    processAuthConfig(LS.config, LS.auth)

  if LS.auth == newJNull():
    # Attempt to retrieve auth.json from system documents
    let options = newQueryOptions(true)
    let rawDoc = LS.store.retrieveRawDocument("auth.json", options)
    if rawDoc != "":
      LS.auth = rawDoc.parseJson()["data"]

  # Validation
  if LS.directory == "" and (LS.operation in [opDelete, opImport, opExport] or LS.mount):
    fail(105, "--directory option not specified.")

  if LS.execution.file == "" and (LS.execution.operation in ["put", "post", "patch"]):
    fail(109, "--file option not specified")

  if LS.execution.uri == "" and LS.operation == opExecute:
    fail(110, "--uri option not specified")

  if LS.execution.operation == "" and LS.operation == opExecute:
    fail(111, "--operation option not specified")

# stores: {
#   test: {
#     file: 'path/to/test.db',
#     config: {
#       resources: {},
#       signature: ''
#     }
#   }
# }
proc initStores() =
  if LS.config.kind == JObject and LS.config.hasKey("stores"):
    for k, v in LS.config["stores"].pairs:
      # TODO error handling
      LSDICT[k] = initLiteStore()
      LSDICT[k].file = v["file"].getStr
      if v.hasKey("config"):
        LSDICT[k].config = v["config"]
  for k in LSDICT.keys:
    LOG.info("Initializing store '$1'" % k)
    LSDICT[k].setup(true)
    LSDICT[k].initStore()
  LOG.info("Initializing main store")
  LS.setup(true)
  LS.initStore()
  LSDICT["main"] = LS

when isMainModule:

  # Manage vacuum operation separately
  if LS.operation == opVacuum:
    LS.setup(false)
    vacuum LS.file
  else:
    # Open Datastore
    #LS.setup(true)
    initStores()
    case LS.operation:
      of opRun:
        LS.serve
        runForever()
      of opImport:
        LS.store.importDir(LS.directory, LS.manageSystemData)
      of opExport:
        LS.store.exportDir(LS.directory, LS.manageSystemData)
      of opDelete:
        LS.store.deleteDir(LS.directory, LS.manageSystemData)
      of opOptimize:
        LS.store.optimize
      of opExecute:
        executeOperation()
      else:
        discard

else:

  proc params*(query: string): StringTableRef =
    new(result)
    let pairs = query.split("&")
    for pair in pairs:
      let data = pair.split("=")
      result[data[0]] = data[1]

  proc query*(table: StringTableRef): string =
    var params = newSeq[string](0)
    for key, value in pairs(table):
      params.add("$1=$2" % @[key, value])
    return params.join("&")

  proc newLSRequest(meth: HttpMethod, resource, id,  body = "", params = newStringTable(), headers = newHttpHeaders()): LSRequest =
    result.reqMethod = meth
    result.body = body
    result.headers = headers
    result.url = parseUri("$1://$2:$3/$4/$5?$6" % @["http", "localhost", "9500", resource, id, params.query()])

  # Public API: Low-level

  proc getInfo*(): LSResponse =
    return LS.getInfo(newLSRequest("info"))

  proc getRawDocuments*(options = newQueryOptions()): LSResponse =
    return LS.getRawDocuments(options, newLSRequest("docs"))

  proc getDocument*(id: string, options = newQueryOptions()): LSResponse =
    return LS.getDocument(id, options, newLSRequest("docs", id))

  proc getRawDocument*(id: string, options = newQueryOptions()): LSResponse =
    return LS.getRawDocument(id, options, newLSRequest("docs", id))

  proc deleteDocument*(id: string): LSResponse =
    return LS.deleteDocument(id, newLSRequest("docs", id))

  proc postDocument*(body, ct: string, folder=""): LSResponse =
    return LS.postDocument(body, ct, folder, newLSRequest("docs", "", body))

  proc putDocument*(id, body, ct: string): LSResponse =
    return LS.putDocument(id, body, ct newLSRequest("docs", id, body))

  proc patchDocument*(id, body: string): LSResponse =
    return LS.patchDocument(id, body, newLSRequest("docs", id, body))

  # Public API: High-level

  proc get*(resource, id: string, params = newStringTable(), headers = newHttpHeaders()): LSResponse =
    return newLSRequest(HttpGet, resource, id, "", params, headers).get(LS, resource, id)

  proc post*(resource, folder, body: string, headers = newHttpHeaders()): LSResponse =
    return newLSRequest(HttpPost, resource, "", body, newStringTable(), headers).post(LS, resource, folder & "/")

  proc put*(resource, id, body: string, headers = newHttpHeaders()): LSResponse =
    return newLSRequest(HttpPut, resource, id, body, newStringTable(), headers).put(LS, resource, id)

  proc patch*(resource, id, body: string, headers = newHttpHeaders()): LSResponse =
    return newLSRequest(HttpPatch, resource, id, body, newStringTable(), headers).patch(LS, resource, id)

  proc delete*(resource, id: string, headers = newHttpHeaders()): LSResponse =
    return newLSRequest(HttpPatch, resource, id, "", newStringTable(), headers).delete(LS, resource, id)

  proc head*(resource, id: string, headers = newHttpHeaders()): LSResponse =
    return newLSRequest(HttpHead, resource, id, "", newStringTable(), headers).head(LS, resource, id)

  proc options*(resource, id: string, headers = newHttpHeaders()): LSResponse =
    return newLSRequest(HttpOptions, resource, id, "", newStringTable(), headers).options(LS, resource, id)