A Cosmos DB server implementation for testing your applications locally.
License: MIT License
JavaScript 1.83%Shell 1.83%TypeScript 96.33%
cosmosdb-server's Introduction
cosmosdb-server
A Cosmos DB server implementation for testing your apps locally.
const{default: cosmosServer}=require("@vercel/cosmosdb-server");const{ CosmosClient }=require("@azure/cosmos");consthttps=require("https");cosmosServer().listen(3000,()=>{console.log(`Cosmos DB server running at https://localhost:3000`);runClient().catch(console.error);});asyncfunctionrunClient(){constclient=newCosmosClient({endpoint: `https://localhost:3000`,key: "dummy key",// disable SSL verification// since the server uses self-signed certificateagent: https.Agent({rejectUnauthorized: false})});// initialize databases since the server is always empty when it bootsconst{ database }=awaitclient.databases.createIfNotExists({id: 'test-db'});const{ container }=awaitdatabase.containers.createIfNotExists({id: 'test-container'});// use the client// ...}
To choose between listening for HTTP and HTTPS, import the right function.
Any SQL queries except the spatial functions ST_ISVALID and ST_ISVALIDDETAILED. Other spatial functions are supported; however, the ST_DISTANCE function uses centroid distances and results may differ from Cosmos DB values.
It may not support newly added features yet. Please report on the Github issue if you find one.
Developing
To build the project, use yarn build.
To run the server from development code, after building, use node lib/cli.js.
This is from working on compatibility with the CosmosDb CSharp SDK
Error logged request:
{
"method":"GET",
"url":"/dbs/devicesimulation/colls/simulations/docs",
"docdbHeaders":[
"x-ms-documentdb-isquery",
"True",
"x-ms-documentdb-query-enablecrosspartition",
"False",
"x-ms-documentdb-query-iscontinuationexpected",
"False"
],
"response":{
"statusCode":400,
"statusMessage":"Bad Request",
"headers":{
"content-type":"application/json",
"content-location":"https://cosmosdb-sim:3000/dbs/devicesimulation/colls/simulations/docs",
"connection":"close",
"x-ms-activity-id":"5879c77f-a5fe-432a-a4d2-4d9454658713",
"x-ms-request-charge":"1"
},
"body":{
"message":"no route"
}
},
"errorMessage":null
}```
Expected result:
* Document is returned
Cause:
* Route lookup appends "_QUERY" when it sees that `x-ms-documentdb-isquery` is set.
Proposed fix by the associated PR:
* Restrict route lookup to only add _QUERY and _UPSERT for POST, where they are applicable
In this collection we have some documents with foo field and for some other's it's undefined.
Then when we ran this query, client give us an error and the server reports this:
TypeError: Cannot read property 'bar' of undefined
at $h.paginate.$h.sort.$c.reduce.filter (eval at exports.default (/data/zeit/api/services/cosmos-local/node_modules/@zeit/cosmosdb-query/lib/executor.js:8:21), <anonymous>:8:83)
at Array.filter (<anonymous>)
at eval (eval at exports.default (/data/zeit/api/services/cosmos-local/node_modules/@zeit/cosmosdb-query/lib/executor.js:8:21), <anonymous>:6:15)
at Object.exports.default (/data/zeit/api/services/cosmos-local/node_modules/@zeit/cosmosdb-query/lib/executor.js:13:12)
at Query.exec (/data/zeit/api/services/cosmos-local/node_modules/@zeit/cosmosdb-query/lib/index.js:29:34)
at Documents.query (/data/zeit/api/services/cosmos-local/node_modules/@zeit/cosmosdb-server/lib/account/items.js:53:55)
at _read_items_1.default (/data/zeit/api/services/cosmos-local/node_modules/@zeit/cosmosdb-server/lib/handler/query-documents.js:24:33)
at process._tickCallback (internal/process/next_tick.js:68:7)
$ node lib/cli.js -p 8081
Ready to accept connections at [::]:8081
Then I installed the certificates so connection does not fail due to ssl error (If you are interesting I could write a PR for that, (the current cert.pem does not seems valid)
Then, when I try to connect to Cosmos DB using dotnet sdk, it's stuck
private const string ConnectionString = "AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";
var cosmosClient = new CosmosClientBuilder(ConnectionString)
.Build();
So I ran it in with the debugger and notice those messages spamming in the debug console I can see it try to connect to another port
DocDBTrace Information: 0 : Marking endpoint https://localhost:3000/ unavailable for read
DocDBTrace Information: 0 : Current WriteEndpoints = (https://localhost:3000/) ReadEndpoints = (https://localhost:3000/)
DocDBTrace Information: 0 : Endpoint https://localhost:3000/ unavailable for Read added/updated to unavailableEndpoints with timestamp 12/20/2020 19:29:21
DocDBTrace Information: 0 : Resolving Master service address, forceMasterRefresh: False, currentMaster:
Note: I had to generate my own CA then generate a certificate with CN=localhost then add the CA to /usr/local/share/ca-certificates/ and run sudo update-ca-certificates to pass the https check
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos;
using Microsoft.Azure.Cosmos.Fluent;
using Microsoft.Azure.Cosmos.Linq;
namespace ReproBugCosmosDb
{
class Program
{
public class SomeObject
{
public string Id { get; set; }
public IList<string> SomeData { get; set; } = new List<string>();
}
private static CosmosClient _cosmosClient;
public const string DevConnectionString = @"AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";
public const string DatabaseName = "SomeReproDatabase2";
public const string ContainerId = "SomeContainerName";
static async Task Main(string[] args)
{
_cosmosClient = new CosmosClientBuilder(DevConnectionString)
.WithSerializerOptions(new CosmosSerializationOptions {PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase})
.WithConnectionModeGateway()
.Build();
await ResetDatabaseAsync(DatabaseName);
var database = _cosmosClient.GetDatabase(DatabaseName);
await database.CreateContainerAsync(ContainerId, "/id");
var container = _cosmosClient.GetContainer(DatabaseName, ContainerId);
await container.UpsertItemAsync(new SomeObject {Id = "1", SomeData = new List<string> {"a"}}, new PartitionKey("1"));
await container.UpsertItemAsync(new SomeObject {Id = "2", SomeData = new List<string> {"b"}}, new PartitionKey("2"));
await container.UpsertItemAsync(new SomeObject {Id = "3", SomeData = new List<string> {"c"}}, new PartitionKey("3"));
await container.UpsertItemAsync(new SomeObject {Id = "4", SomeData = new List<string> {"d"}}, new PartitionKey("4"));
try
{
var result = await GetElementsByIds(new List<string> {"1", "2", "3"});
if (!result.OrderBy(x => x).SequenceEqual(new[] {"a", "b", "c"}))
throw new Exception("Invalid result");
Console.WriteLine("Success");
}
catch (CosmosException ex)
{
Console.WriteLine(ex.Diagnostics.ToString());
throw;
}
}
private static async Task ResetDatabaseAsync(string databaseName)
{
await _cosmosClient.CreateDatabaseIfNotExistsAsync(databaseName);
var database = _cosmosClient.GetDatabase(databaseName);
await database.DeleteAsync();
await _cosmosClient.CreateDatabaseIfNotExistsAsync(databaseName);
}
private static async Task<List<string>> GetElementsByIds(IList<string> ids)
{
var container = _cosmosClient.GetContainer(DatabaseName, ContainerId);
var iterator = container.GetItemLinqQueryable<SomeObject>()
.Where(x => ids.Contains(x.Id))
.ToFeedIterator();
var fetchedPhotoDocuments = new List<string>();
while (iterator.HasMoreResults)
{
var item = await iterator.ReadNextAsync().ConfigureAwait(false);
fetchedPhotoDocuments.AddRange(item.Resource.SelectMany(x => x.SomeData).ToList());
}
return fetchedPhotoDocuments.Distinct().ToList();
}
}
}
I discovered the following issues while attempting to make it work:
SDK can not be configured to ignore SSL validation errors. My workaround was using reflection to configure the SDK internals
Addresses endpoint as in #29 is not implemented. Workaround is configuring the C# SDK to use Gateway mode.
Whenever an error occurs (>399 status code), the C# SDK expects a case sensitive message property with non-null value in the response body. Otherwise it will throw a NullReferenceException.
"Meta" / root endpoint must return certain data, otherwise SDK will throw a NullReferenceException. Additionally the queryEngineConfiguration property is required for querying to work.
The C# parses and validates the _rid property. In particular, it requires RID for collections to have a specific bit set to 1 (first bit of 5th byte)
A property on partitionKeyRanges is invalid, it is maxInclusive but should be maxExclusive
C# SDK sends boolean headers with a "True" value instead of "true", causing the server to not handle them as true
C# SDK will query partitionKeys using an "Incremental Feed". See A-IM header. Essentially it expects an etag when retrieving partition keys, and it expects a 302 status code once all keys have been received. Current behavior causes an infinite loop in the C# SDK
After forking this repo and applying fixes for the above I am able to successfully use this server with the C# SDK.
I noticed you have a current draft PR with some fixes for the Java SDK, which will fix some of the issues here. I can make a PR with the remaining fixes if you'd like
This is because the hostname in databaseAccountEndpoint is set to the hostname at startup, however
accessing another service in a docker-compose project requires one to connect to the service name as hostname.
This can be fixed by setting databaseAccountEndpoint to the host in the requests header
we try to integrate your project within our CI/CD build pipeline. One test uses an Upsert command (2nd) to update an existing entry, which was previously added with a first upsert command (1st).
When the 2nd Upsert statement is issued, we get this reply:
{HTTPFailure}Status code: 409 {"code":"Conflict","message":"Resource with specified id or name already exists."}
As far as I understand, Upsert should NEVER return an error like "already exists" since the entry should just be overwritten or inserted. The test runs fine when running it agains a local installation of the Azure CosmosDB Emulator (https://docs.microsoft.com/de-de/azure/cosmos-db/local-emulator).
I'm trying to create a trigger, but is returning a bad request.
Here it is my code
from pydocumentdb import document_client
DB_DATABASE = 'test_database2'
DB_COLLECTION = 'my_collection'
client = document_client.DocumentClient(
'https://localhost:3000/', {'masterKey': ''})
print("deleting database")
try:
db = next((data for data in client.ReadDatabases(
) if data['id'] == DB_DATABASE))
client.DeleteDatabase(db['_self'])
except:
pass
print("creating database")
db = client.CreateDatabase({'id': DB_DATABASE})
print("creating collection")
collection = client.CreateCollection(db['_self'], {'id': DB_COLLECTION})
path = 'dbs/{}/colls/{}'.format(DB_DATABASE, DB_COLLECTION)
# Create trigger
trigger_definition = {
'id': '_type',
'serverScript': """
// Ensures that documents have a _type field.
function validateNameExists() {
var collection = getContext().getCollection();
var request = getContext().getRequest();
var docToCreate = request.getBody();
// Reject documents that do not have a name property by throwing an exception.
if (!docToCreate._type) {
throw new Error('Document must include a "_type" property.');
}
}
""",
'triggerType': 'Pre',
'triggerOperation': 'All'
}
try:
client.CreateTrigger(collection['_self'], trigger_definition)
except Exception as e:
print(e)
The request is created for 'https://localhost:3000//dbs/wgLLAG--C30lC30lC30lD0--/colls/V2u_QG--C30lC30lC30lC0--/triggers/'
<class 'dict'>: {'id': '_type', 'triggerType': 'Pre', 'triggerOperation': 'All', 'body': '\n // Ensures that documents have a _type field.\n function validateNameExists() {\n var collection = getContext().getCollection();\n var request = getContext().getRequest();\n var docToCreate = request.getBody();\n\n // Reject documents that do not have a name property by throwing an exception.\n if (!docToCreate._type) {\n throw new Error(\'Document must include a "_type" property.\');\n }\n }\n '}```
I've set it up with docker-compose and have generated a self-signed CA certificate for the assigned hostname, and added it to the device simulation container, so when it connects using the Azure CSharp SDK, all SSL checks out and it just works(tm), aside from a few quirks that I had to look at (#46 and #48).
In doing this, I found a need for two main things:
Adding optional paths for an external cert and cert key to cosmosdb-server
Adding more default logging for the requests and responses
My solution was to take the index.js (after compilation) and provide a replacement instead, packaging it with the docker image.
It appears that the delete-database-endpoint returns nothing (empty response), which is unexpected (at least to the Node SDK). Test case to reproduce shown below.
I can't seem to find any detailed license information within this project. The package.json states that the license is MIT, but it would be good for confidence if this was corroborated by a LICENSE file in the project root. Would you mind adding one, or accepting one via a PR?
Self explanatory,
when creating a simple azure function app with a cosmosDB input and adding a connection string in environment variables,
despite the connection string refering to "http://..." it will always try to connect to "https://...".
This is because databaseAccountEndpoint is hardcoded to be https
With the official CosmosDB emulator not running on non-windows, this is more or less exactly what I'm looking for. I was however not able to use it together with the Java SDK.
It seems like the Node SDK is quite lenient and performs little to no validation on the resource ids*. Hence, generating RID's like you do probably work (I haven't actually tested your implementation with the Node SDK, but I assume it does given the readme etc).
The Java SDK however is a bit more strict and assigns much more meaning to them, as shown here. In addition to be accepted by the parser, they also need to successfully serialize back to the original string.
Since your implementation only generates a quite random ID (of 14 bytes?), the Java SDK will fail on inserting documents, as shown below.
java.lang.IllegalArgumentException: Invalid resource id PEtvD0--C30lC30lC30lC0--
at com.microsoft.azure.documentdb.internal.ResourceId.parse(ResourceId.java:57)
at com.microsoft.azure.documentdb.internal.routing.CollectionCache.resolveByRid(CollectionCache.java:116)
at com.microsoft.azure.documentdb.internal.routing.CollectionCache.resolveCollection(CollectionCache.java:49)
at com.microsoft.azure.documentdb.internal.SessionContainer.resolvePartitionKeyRange(SessionContainer.java:217)
at com.microsoft.azure.documentdb.internal.SessionContainer.resolveSessionToken(SessionContainer.java:123)
at com.microsoft.azure.documentdb.DocumentClient.applySessionToken(DocumentClient.java:3222)
at com.microsoft.azure.documentdb.DocumentClient.doQuery(DocumentClient.java:3143)
at com.microsoft.azure.documentdb.DocumentQueryClientInternal.doQuery(DocumentQueryClientInternal.java:47)
at com.microsoft.azure.documentdb.internal.query.AbstractQueryExecutionContext.executeRequest(AbstractQueryExecutionContext.java:219)
at com.microsoft.azure.documentdb.internal.query.DefaultQueryExecutionContext.executeOnce(DefaultQueryExecutionContext.java:159)
at com.microsoft.azure.documentdb.internal.query.DefaultQueryExecutionContext.fillBuffer(DefaultQueryExecutionContext.java:99)
at com.microsoft.azure.documentdb.internal.query.DefaultQueryExecutionContext.hasNext(DefaultQueryExecutionContext.java:71)
at com.microsoft.azure.documentdb.internal.query.ProxyQueryExecutionContext.<init>(ProxyQueryExecutionContext.java:67)
at com.microsoft.azure.documentdb.internal.query.QueryExecutionContextFactory.createQueryExecutionContext(QueryExecutionContextFactory.java:23)
at com.microsoft.azure.documentdb.QueryIterable.createQueryExecutionContext(QueryIterable.java:70)
at com.microsoft.azure.documentdb.QueryIterable.reset(QueryIterable.java:115)
at com.microsoft.azure.documentdb.QueryIterable.<init>(QueryIterable.java:57)
at com.microsoft.azure.documentdb.DocumentClient.queryDocuments(DocumentClient.java:1167)
at com.microsoft.azure.documentdb.DocumentClient.queryDocuments(DocumentClient.java:1138)
* The source linked is of a quite old version. I can't seem to find the source for the most recent version of the Java SDK anywhere, reported here. This is obviously quite unfortunate, who knows what the SDK is doing these days.
The read-meta handler hardcodes port 3000, which is incorrect when running the server on another port. This causes the Python client to throw a connection refused exception after connecting to a server on another port:
<urllib3.connection.HTTPSConnection object at 0x7fd48863dfd0>: Failed to establish a new connection: [Errno 111] Connection refused
due to the client trying to communicate with port 3000, because of the hard coded values.
This can be solved by passing server options to handlers, so that the port can be dynamically generated; this would be a lot of code changes so perhaps there's an easier way to avoid this?
I'm trying to use cosmosdb-server with the NuGet package Microsoft.EntityFrameworkCore.Cosmos version 3.1.0 and get a NullReferenceException during application startup when calling .Database.EnsureCreated():
System.NullReferenceException: Object reference not set to an instance of an object.
crit: Microsoft.AspNetCore.Hosting.Diagnostics[6]
Application startup exception
System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Azure.Cosmos.CosmosAccountServiceConfiguration.get_DefaultConsistencyLevel()
at Microsoft.Azure.Cosmos.DocumentClient.GetInitializationTaskAsync(IStoreClientFactory storeClientFactory)
at Microsoft.Azure.Cosmos.DocumentClient.EnsureValidClientAsync()
at Microsoft.Azure.Cosmos.Handlers.RequestInvokerHandler.EnsureValidClientAsync(RequestMessage request)
at Microsoft.Azure.Cosmos.Handlers.RequestInvokerHandler.SendAsync(RequestMessage request, CancellationToken cancellationToken)
at Microsoft.Azure.Cosmos.Handlers.RequestInvokerHandler.SendAsync(Uri resourceUri, ResourceType resourceType, OperationType operationType, RequestOptions requestOptions, ContainerCore cosmosContainerCore, Nullable`1 partitionKey, Stream streamPayload, Action`1 requestEnricher, CancellationToken cancellationToken)
at Microsoft.Azure.Cosmos.CosmosClient.CreateDatabaseIfNotExistsAsync(String id, Nullable`1 throughput, RequestOptions requestOptions, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Cosmos.Storage.Internal.CosmosClientWrapper.CreateDatabaseIfNotExistsOnceAsync(DbContext _, Object __, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Cosmos.Storage.Internal.CosmosClientWrapper.CreateDatabaseIfNotExistsOnce(DbContext context, Object state)
at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.ExecuteImplementation[TState,TResult](Func`3 operation, Func`3 verifySucceeded, TState state)
at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.Cosmos.Storage.Internal.CosmosClientWrapper.CreateDatabaseIfNotExists()
at Microsoft.EntityFrameworkCore.Cosmos.Storage.Internal.CosmosDatabaseCreator.EnsureCreated()
at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.EnsureCreated()
at testclient.Startup.Configure(IApplicationBuilder app, IWebHostEnvironment env, TestContext dbContext) in /home/martin/projects/cosmosdb-server/testclient/Startup.cs:line 34
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
at Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.<Build>b__0(IApplicationBuilder builder)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass13_0.<UseStartup>b__2(IApplicationBuilder app)
at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.GenericWebHostService.StartAsync(CancellationToken cancellationToken)
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Azure.Cosmos.CosmosAccountServiceConfiguration.get_DefaultConsistencyLevel()
at Microsoft.Azure.Cosmos.DocumentClient.GetInitializationTaskAsync(IStoreClientFactory storeClientFactory)
at Microsoft.Azure.Cosmos.DocumentClient.EnsureValidClientAsync()
at Microsoft.Azure.Cosmos.Handlers.RequestInvokerHandler.EnsureValidClientAsync(RequestMessage request)
at Microsoft.Azure.Cosmos.Handlers.RequestInvokerHandler.SendAsync(RequestMessage request, CancellationToken cancellationToken)
at Microsoft.Azure.Cosmos.Handlers.RequestInvokerHandler.SendAsync(Uri resourceUri, ResourceType resourceType, OperationType operationType, RequestOptions requestOptions, ContainerCore cosmosContainerCore, Nullable`1 partitionKey, Stream streamPayload, Action`1 requestEnricher, CancellationToken cancellationToken)
at Microsoft.Azure.Cosmos.CosmosClient.CreateDatabaseIfNotExistsAsync(String id, Nullable`1 throughput, RequestOptions requestOptions, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Cosmos.Storage.Internal.CosmosClientWrapper.CreateDatabaseIfNotExistsOnceAsync(DbContext _, Object __, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Cosmos.Storage.Internal.CosmosClientWrapper.CreateDatabaseIfNotExistsOnce(DbContext context, Object state)
at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.ExecuteImplementation[TState,TResult](Func`3 operation, Func`3 verifySucceeded, TState state)
at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.Cosmos.Storage.Internal.CosmosClientWrapper.CreateDatabaseIfNotExists()
at Microsoft.EntityFrameworkCore.Cosmos.Storage.Internal.CosmosDatabaseCreator.EnsureCreated()
at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.EnsureCreated()
at testclient.Startup.Configure(IApplicationBuilder app, IWebHostEnvironment env, TestContext dbContext) in /home/martin/projects/cosmosdb-server/testclient/Startup.cs:line 34
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
at Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.<Build>b__0(IApplicationBuilder builder)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass13_0.<UseStartup>b__2(IApplicationBuilder app)
at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.GenericWebHostService.StartAsync(CancellationToken cancellationToken)
at Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken cancellationToken)
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host)
at testclient.Program.Main(String[] args) in /home/martin/projects/cosmosdb-server/testclient/Program.cs:line 16
It seems to expect some data about consistency levels being returned from Cosmos.
Minimal example can be created by:
Creating a new ASP.NET Core project with dotnet 3.1: dotnet new web
Creating empty DbContext:
public class TestContext : DbContext {
public TestContext(DbContextOptions options) : base(options){}
}
Configuring Cosmos DB in Startup and asking it to create a new DB.
public class Startup
{
public void ConfigureServices(IServiceCollection services) {
services.AddDbContext<TestContext>(opt =>
{
opt.UseCosmos("https://localhost:8081", "ZHVtbXk=", "some-db");
});
}
public void Configure(TestContext dbContext) {
dbContext.Database.EnsureCreated();
}
}
When creating a function app and a function with cosmosdb input binding and a sqlquery,
two post requests are made to "/dbs/:dbId/colls/:collId/docs", one of which has the "x-ms-cosmos-is-query-plan-request: True" header.
The Azure function expects a specific response from this request, after which the actual query request will be made.
The expected resposne looks like this:
with attribute values depending on the specific query, for instance if "order by" is added, the attributes
orderBy and orderByExpressions will contain "Ascending/Descending" and the column names respectively
Any interest in publishing a docker image for this? I'm using this Dockerfile in an integration testing story via docker-compose and it appears to be working great
I am trying to use the cosmosdb-server for testing an ASP.net core application, but I always get an exception when trying to interact with the server: System.Net.Http.HttpRequestException : The SSL connection could not be established, see inner exception. ---- System.Security.Authentication.AuthenticationException : The remote certificate is invalid according to the validation procedure.
Did I do something wrong?
I did not find a way to disable SSL certificate verification for CosmosClient.
I know, that the older DocumentClient has an option to pass a custom handler to ignore the SSL certificate, but there does not seem to be such an option for the CosmosClient.