Skip to content

Add initial PostgreSQL implementation for get & put operations - #5

Merged
G8XSU merged 2 commits into
lightningdevkit:mainfrom
G8XSU:postgres-impl-get-put
Apr 21, 2023
Merged

Add initial PostgreSQL implementation for get & put operations#5
G8XSU merged 2 commits into
lightningdevkit:mainfrom
G8XSU:postgres-impl-get-put

Conversation

@G8XSU

@G8XSUG8XSU commented Jan 13, 2023

Copy link
Copy Markdown
Contributor

TestStrategy

How?

  • PostgresIntegrationTest uses testcontainers to spin up docker containers for each test.
  • AbstractKVStoreIntegrationTest defines behavior that every impl of KVStore needs to follow. Different impl's can re-use the same abstract class to test their impl against it.
  • We will keep on adding tests to this as we add more impl details.

@G8XSU
G8XSU requested a review from jkczyzJanuary 13, 2023 01:58
@G8XSUG8XSU changed the title Add basic PostgreSQL implementation for get & put operationsAdd initial PostgreSQL implementation for get & put operationsJan 13, 2023
@G8XSU
G8XSU requested a review from devrandomJanuary 17, 2023 22:36
Comment threadapp/src/main/java/org/vss/impl/postgres/sql/v0_create_vss_db.sql Outdated
Comment threadapp/build.gradle Outdated
main {
generateSchemaSourceOnCompilation = true

generationTool {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we need to make a decision if we check in the generated Java code or not. personally, I'm a bit uncomfortable with generating code on the fly on prod machines, but let's see what other people think.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Discussed this offline. Prefer to check in the code but also provide a way for users to generate it at as an option to the build process.

Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated

VssDbRecord globalVersionRecord = buildVssRecord(storeId,
KeyValue.newBuilder()
.setKey(GLOBAL_VERSION_KEY)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the global version should be stored in a separate table. otherwise, you have to make sure the caller doesn't try to use this key, and it seems messy.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The advantage is that it can be treated as any other keyvalue and easily handled with exactly same cases.

Other consideration is, if we want client to be able to override global_version in certain scenarios. My take is we should allow, end of the day its their storage and versioning, they can do whatever they want with it.

There is also case where client just wants to do a "get" on global_version.
For all purposes, it seems simpler to keep it as normal key-value, otherwise i will need to introduce additional code to support everything.

One case that we will have to handle separately from normal key-value is to not return global_version as part of ListKeyVersions api. (we have dedicated field in response for it)

Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated
Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated
Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated
Comment threadapp/build.gradle Outdated
@devrandom

Copy link
Copy Markdown
Member

also, would be good to have an integration test. not sure if it's better to have it against postgres (more precise model of a production environment) or against a lightweight in-memory SQL DB (faster to run the tests).

.setKey(GLOBAL_VERSION_KEY)
.setVersion(request.getGlobalVersion())
.build());
if (request.hasGlobalVersion()) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this doesn't increment the global version when it's not specified in the request. we always want to increment it, right?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess we could have the specifications say that it doesn't get incremented if not present in the request, but we should be explicit about it, since the developer might not expect that

@G8XSUG8XSUJan 25, 2023

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Based on how optimistic locking works, version needs to be provided by client in order to enact it.
So expectation is that we don't increment it and dont perform the check if developer doesn't supply it.

If global_version is not supplied, it means it is a non-global-version-check-required write.
We shouldn't be incrementing global_version in this case as client-side will not increment and has no way of knowing this without performing a sync.

Based on different application needs, some might not need a global_version check on every write, and this feature is meant to support those applications.

@G8XSU

Copy link
Copy Markdown
ContributorAuthor

Added an integration test for AbstractKVStore and PostgresIntegration test uses it.
Can review it as part of this PR or we can separate it out as well in #5

postgreSQLContainer.getUsername(), postgreSQLContainer.getPassword());
DSLContext dslContext = DSL.using(conn, SQLDialect.POSTGRES);

this.kvStore = new PostgresBackendImpl(dslContext);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

don't we need to close the previous DB connection, otherwise we may run out of file descriptors or such if we have many tests?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Each and every test spins up new db cluster/instance so db connection shouldn't really be a problem.
But I added a AfterEach block to destroy connection in any case.

For production, we are using connection pool and DSL.using(dataSource, dialect) where jooq/pool does the connection management for us.

@G8XSU
G8XSU marked this pull request as ready for review January 26, 2023 01:38

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to get through the tests still

Comment threadapp/build.gradle Outdated
main {
generateSchemaSourceOnCompilation = true

generationTool {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Discussed this offline. Prefer to check in the code but also provide a way for users to generate it at as an option to the build process.


ListKeyVersionsResponse listKeyVersions(ListKeyVersionsRequest request);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: no blanks at end of file here and throughout

@@ -0,0 +1,8 @@
CREATE TABLE vss_db (
store_id character varying(120) NOT NULL,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a convention to have two spaces before NULL / NOT NULL?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

idk, just a copy-paste side-effect from describe table in postgres i guess, will replace with single spaces.

store_id character varying(120) NOT NULL,
key character varying(120) NOT NULL,
value bytea NULL,
version bigint NOT NULL,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was the choice of using a signed integer in the vss.proto based on the fact the database doesn't support unsigned types?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mostly because many languages(kotlin/java/python) don't have good support for unsigned values.
So we avoid using them directly in interface if possible. (had this feedback from cashapp as well)

Comment on lines +49 to +54
dslContext.execute("CREATE TABLE vss_db ("
+ "store_id character varying(120) NOT NULL CHECK (store_id <> ''),"
+ "key character varying(120) NOT NULL,"
+ "value bytea NULL,"
+ "version bigint NOT NULL,"
+ "PRIMARY KEY (store_id, key));");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be possible to take this from the sql file?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that the sql file is present only for documentation purpose and git history.
Its not going to be directly used in db creation, will need to be done manually.
I wanted to avoid a filepath dependency in tests, let me know your thoughts.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could creation be accomplished through a script / program that reads the schema?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

jooq doesn't create table for us and we assume in production that db schema is already created.
In tests however we are creating a fresh instance of db for every test and need to create table/schema everytime.


private void createTable(DSLContext dslContext) {
dslContext.execute("CREATE TABLE vss_db ("
+ "store_id character varying(120) NOT NULL CHECK (store_id <> ''),"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why does this line differ from the sql file?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will fix this.

Comment on lines +53 to +56
} else {
keyValue = KeyValue.newBuilder()
.setKey(request.getKey()).build();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we return an error if there is no record for the key?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think an empty response is preferable in this case.
ResourceNotFound or 404 might represent a myriad of issues and things going wrong. (url wrong etc.)
In this case, we consider it a perfectly valid request to get a key which does not exist or to check existence of a key.
I see no harm in mixing keys that exist with no data and keys which don't exist, to make clients life easier instead of throwing an exception in one case.

Note: This is only applicable if client has permission to storeId, if not then we would want to throw ResourceNotFound.

However, this is a controversial topic and there are reasons to go either way.

Comment on lines +49 to +54
dslContext.execute("CREATE TABLE vss_db ("
+ "store_id character varying(120) NOT NULL CHECK (store_id <> ''),"
+ "key character varying(120) NOT NULL,"
+ "value bytea NULL,"
+ "version bigint NOT NULL,"
+ "PRIMARY KEY (store_id, key));");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could creation be accomplished through a script / program that reads the schema?

KeyValue response = getObject("non_existent_key");

assertThat(response.getKey(), is("non_existent_key"));
assertTrue(response.getValue().isEmpty());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also check that version is empty / zero?

Comment on lines +86 to +94
int[] batchResult = dsl.batch(batchQueries).execute();

for (int numOfRowsUpdated : batchResult) {
if (numOfRowsUpdated == 0) {
throw new ConflictException(
"Transaction could not be completed due to a possible conflict");
}
}
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you test the case where one key failing causes the entire transaction to fail? (i.e., the successful key is not updated)

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like some of the comments for the first commit were resolved in the second commit. You'll want to make sure they are resolved in the right commit so that they are self-contained. Otherwise, looks good and sorry about the delay.

PRIMARY KEY (store_id, key)
);

); No newline at end of file

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add newline.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I earlier got comment about removing newlines/blanks at end of files,
bit confused, let me know if i misunderstood.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, please disregard. I thought that Github was showing the "No newline at end of file" symbol, but I guess I was mistaken.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, i might have fixed it,
So just to clarify there "should" be a newline at EOF?

Addressed other comments as well.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, it should contain a newline, just not an empty line.

@G8XSU
G8XSUforce-pushed the postgres-impl-get-put branch from 344779e to 403b0c2CompareApril 21, 2023 00:03
@G8XSU
G8XSU merged commit 5de859d into lightningdevkit:mainApr 21, 2023
@G8XSUG8XSU mentioned this pull request May 10, 2023
31 tasks
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

@G8XSU@devrandom@jkczyz
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Add initial PostgreSQL implementation for get & put operations by G8XSU · Pull Request #5 · lightningdevkit/vss-server · GitHub
Skip to content

Add initial PostgreSQL implementation for get & put operations - #5

Merged
G8XSU merged 2 commits into
lightningdevkit:mainfrom
G8XSU:postgres-impl-get-put
Apr 21, 2023
Merged

Add initial PostgreSQL implementation for get & put operations#5
G8XSU merged 2 commits into
lightningdevkit:mainfrom
G8XSU:postgres-impl-get-put

Conversation

@G8XSU

@G8XSUG8XSU commented Jan 13, 2023

Copy link
Copy Markdown
Contributor

TestStrategy

How?

  • PostgresIntegrationTest uses testcontainers to spin up docker containers for each test.
  • AbstractKVStoreIntegrationTest defines behavior that every impl of KVStore needs to follow. Different impl's can re-use the same abstract class to test their impl against it.
  • We will keep on adding tests to this as we add more impl details.

@G8XSU
G8XSU requested a review from jkczyzJanuary 13, 2023 01:58
@G8XSUG8XSU changed the title Add basic PostgreSQL implementation for get & put operationsAdd initial PostgreSQL implementation for get & put operationsJan 13, 2023
@G8XSU
G8XSU requested a review from devrandomJanuary 17, 2023 22:36
Comment threadapp/src/main/java/org/vss/impl/postgres/sql/v0_create_vss_db.sql Outdated
Comment threadapp/build.gradle Outdated
main {
generateSchemaSourceOnCompilation = true

generationTool {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we need to make a decision if we check in the generated Java code or not. personally, I'm a bit uncomfortable with generating code on the fly on prod machines, but let's see what other people think.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Discussed this offline. Prefer to check in the code but also provide a way for users to generate it at as an option to the build process.

Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated

VssDbRecord globalVersionRecord = buildVssRecord(storeId,
KeyValue.newBuilder()
.setKey(GLOBAL_VERSION_KEY)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the global version should be stored in a separate table. otherwise, you have to make sure the caller doesn't try to use this key, and it seems messy.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The advantage is that it can be treated as any other keyvalue and easily handled with exactly same cases.

Other consideration is, if we want client to be able to override global_version in certain scenarios. My take is we should allow, end of the day its their storage and versioning, they can do whatever they want with it.

There is also case where client just wants to do a "get" on global_version.
For all purposes, it seems simpler to keep it as normal key-value, otherwise i will need to introduce additional code to support everything.

One case that we will have to handle separately from normal key-value is to not return global_version as part of ListKeyVersions api. (we have dedicated field in response for it)

Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated
Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated
Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated
Comment threadapp/build.gradle Outdated
@devrandom

Copy link
Copy Markdown
Member

also, would be good to have an integration test. not sure if it's better to have it against postgres (more precise model of a production environment) or against a lightweight in-memory SQL DB (faster to run the tests).

.setKey(GLOBAL_VERSION_KEY)
.setVersion(request.getGlobalVersion())
.build());
if (request.hasGlobalVersion()) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this doesn't increment the global version when it's not specified in the request. we always want to increment it, right?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess we could have the specifications say that it doesn't get incremented if not present in the request, but we should be explicit about it, since the developer might not expect that

@G8XSUG8XSUJan 25, 2023

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Based on how optimistic locking works, version needs to be provided by client in order to enact it.
So expectation is that we don't increment it and dont perform the check if developer doesn't supply it.

If global_version is not supplied, it means it is a non-global-version-check-required write.
We shouldn't be incrementing global_version in this case as client-side will not increment and has no way of knowing this without performing a sync.

Based on different application needs, some might not need a global_version check on every write, and this feature is meant to support those applications.

@G8XSU

Copy link
Copy Markdown
ContributorAuthor

Added an integration test for AbstractKVStore and PostgresIntegration test uses it.
Can review it as part of this PR or we can separate it out as well in #5

postgreSQLContainer.getUsername(), postgreSQLContainer.getPassword());
DSLContext dslContext = DSL.using(conn, SQLDialect.POSTGRES);

this.kvStore = new PostgresBackendImpl(dslContext);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

don't we need to close the previous DB connection, otherwise we may run out of file descriptors or such if we have many tests?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Each and every test spins up new db cluster/instance so db connection shouldn't really be a problem.
But I added a AfterEach block to destroy connection in any case.

For production, we are using connection pool and DSL.using(dataSource, dialect) where jooq/pool does the connection management for us.

@G8XSU
G8XSU marked this pull request as ready for review January 26, 2023 01:38

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to get through the tests still

Comment threadapp/build.gradle Outdated
main {
generateSchemaSourceOnCompilation = true

generationTool {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Discussed this offline. Prefer to check in the code but also provide a way for users to generate it at as an option to the build process.


ListKeyVersionsResponse listKeyVersions(ListKeyVersionsRequest request);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: no blanks at end of file here and throughout

@@ -0,0 +1,8 @@
CREATE TABLE vss_db (
store_id character varying(120) NOT NULL,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a convention to have two spaces before NULL / NOT NULL?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

idk, just a copy-paste side-effect from describe table in postgres i guess, will replace with single spaces.

store_id character varying(120) NOT NULL,
key character varying(120) NOT NULL,
value bytea NULL,
version bigint NOT NULL,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was the choice of using a signed integer in the vss.proto based on the fact the database doesn't support unsigned types?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mostly because many languages(kotlin/java/python) don't have good support for unsigned values.
So we avoid using them directly in interface if possible. (had this feedback from cashapp as well)

Comment on lines +49 to +54
dslContext.execute("CREATE TABLE vss_db ("
+ "store_id character varying(120) NOT NULL CHECK (store_id <> ''),"
+ "key character varying(120) NOT NULL,"
+ "value bytea NULL,"
+ "version bigint NOT NULL,"
+ "PRIMARY KEY (store_id, key));");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be possible to take this from the sql file?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that the sql file is present only for documentation purpose and git history.
Its not going to be directly used in db creation, will need to be done manually.
I wanted to avoid a filepath dependency in tests, let me know your thoughts.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could creation be accomplished through a script / program that reads the schema?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

jooq doesn't create table for us and we assume in production that db schema is already created.
In tests however we are creating a fresh instance of db for every test and need to create table/schema everytime.


private void createTable(DSLContext dslContext) {
dslContext.execute("CREATE TABLE vss_db ("
+ "store_id character varying(120) NOT NULL CHECK (store_id <> ''),"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why does this line differ from the sql file?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will fix this.

Comment on lines +53 to +56
} else {
keyValue = KeyValue.newBuilder()
.setKey(request.getKey()).build();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we return an error if there is no record for the key?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think an empty response is preferable in this case.
ResourceNotFound or 404 might represent a myriad of issues and things going wrong. (url wrong etc.)
In this case, we consider it a perfectly valid request to get a key which does not exist or to check existence of a key.
I see no harm in mixing keys that exist with no data and keys which don't exist, to make clients life easier instead of throwing an exception in one case.

Note: This is only applicable if client has permission to storeId, if not then we would want to throw ResourceNotFound.

However, this is a controversial topic and there are reasons to go either way.

Comment on lines +49 to +54
dslContext.execute("CREATE TABLE vss_db ("
+ "store_id character varying(120) NOT NULL CHECK (store_id <> ''),"
+ "key character varying(120) NOT NULL,"
+ "value bytea NULL,"
+ "version bigint NOT NULL,"
+ "PRIMARY KEY (store_id, key));");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could creation be accomplished through a script / program that reads the schema?

KeyValue response = getObject("non_existent_key");

assertThat(response.getKey(), is("non_existent_key"));
assertTrue(response.getValue().isEmpty());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also check that version is empty / zero?

Comment on lines +86 to +94
int[] batchResult = dsl.batch(batchQueries).execute();

for (int numOfRowsUpdated : batchResult) {
if (numOfRowsUpdated == 0) {
throw new ConflictException(
"Transaction could not be completed due to a possible conflict");
}
}
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you test the case where one key failing causes the entire transaction to fail? (i.e., the successful key is not updated)

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like some of the comments for the first commit were resolved in the second commit. You'll want to make sure they are resolved in the right commit so that they are self-contained. Otherwise, looks good and sorry about the delay.

PRIMARY KEY (store_id, key)
);

); No newline at end of file

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add newline.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I earlier got comment about removing newlines/blanks at end of files,
bit confused, let me know if i misunderstood.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, please disregard. I thought that Github was showing the "No newline at end of file" symbol, but I guess I was mistaken.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, i might have fixed it,
So just to clarify there "should" be a newline at EOF?

Addressed other comments as well.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, it should contain a newline, just not an empty line.

@G8XSU
G8XSUforce-pushed the postgres-impl-get-put branch from 344779e to 403b0c2CompareApril 21, 2023 00:03
@G8XSU
G8XSU merged commit 5de859d into lightningdevkit:mainApr 21, 2023
@G8XSUG8XSU mentioned this pull request May 10, 2023
31 tasks
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

@G8XSU@devrandom@jkczyz
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Add initial PostgreSQL implementation for get & put operations by G8XSU · Pull Request #5 · lightningdevkit/vss-server · GitHub
Skip to content

Add initial PostgreSQL implementation for get & put operations - #5

Merged
G8XSU merged 2 commits into
lightningdevkit:mainfrom
G8XSU:postgres-impl-get-put
Apr 21, 2023
Merged

Add initial PostgreSQL implementation for get & put operations#5
G8XSU merged 2 commits into
lightningdevkit:mainfrom
G8XSU:postgres-impl-get-put

Conversation

@G8XSU

@G8XSUG8XSU commented Jan 13, 2023

Copy link
Copy Markdown
Contributor

TestStrategy

How?

  • PostgresIntegrationTest uses testcontainers to spin up docker containers for each test.
  • AbstractKVStoreIntegrationTest defines behavior that every impl of KVStore needs to follow. Different impl's can re-use the same abstract class to test their impl against it.
  • We will keep on adding tests to this as we add more impl details.

@G8XSU
G8XSU requested a review from jkczyzJanuary 13, 2023 01:58
@G8XSUG8XSU changed the title Add basic PostgreSQL implementation for get & put operationsAdd initial PostgreSQL implementation for get & put operationsJan 13, 2023
@G8XSU
G8XSU requested a review from devrandomJanuary 17, 2023 22:36
Comment threadapp/src/main/java/org/vss/impl/postgres/sql/v0_create_vss_db.sql Outdated
Comment threadapp/build.gradle Outdated
main {
generateSchemaSourceOnCompilation = true

generationTool {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we need to make a decision if we check in the generated Java code or not. personally, I'm a bit uncomfortable with generating code on the fly on prod machines, but let's see what other people think.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Discussed this offline. Prefer to check in the code but also provide a way for users to generate it at as an option to the build process.

Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated

VssDbRecord globalVersionRecord = buildVssRecord(storeId,
KeyValue.newBuilder()
.setKey(GLOBAL_VERSION_KEY)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the global version should be stored in a separate table. otherwise, you have to make sure the caller doesn't try to use this key, and it seems messy.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The advantage is that it can be treated as any other keyvalue and easily handled with exactly same cases.

Other consideration is, if we want client to be able to override global_version in certain scenarios. My take is we should allow, end of the day its their storage and versioning, they can do whatever they want with it.

There is also case where client just wants to do a "get" on global_version.
For all purposes, it seems simpler to keep it as normal key-value, otherwise i will need to introduce additional code to support everything.

One case that we will have to handle separately from normal key-value is to not return global_version as part of ListKeyVersions api. (we have dedicated field in response for it)

Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated
Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated
Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated
Comment threadapp/build.gradle Outdated
@devrandom

Copy link
Copy Markdown
Member

also, would be good to have an integration test. not sure if it's better to have it against postgres (more precise model of a production environment) or against a lightweight in-memory SQL DB (faster to run the tests).

.setKey(GLOBAL_VERSION_KEY)
.setVersion(request.getGlobalVersion())
.build());
if (request.hasGlobalVersion()) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this doesn't increment the global version when it's not specified in the request. we always want to increment it, right?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess we could have the specifications say that it doesn't get incremented if not present in the request, but we should be explicit about it, since the developer might not expect that

@G8XSUG8XSUJan 25, 2023

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Based on how optimistic locking works, version needs to be provided by client in order to enact it.
So expectation is that we don't increment it and dont perform the check if developer doesn't supply it.

If global_version is not supplied, it means it is a non-global-version-check-required write.
We shouldn't be incrementing global_version in this case as client-side will not increment and has no way of knowing this without performing a sync.

Based on different application needs, some might not need a global_version check on every write, and this feature is meant to support those applications.

@G8XSU

Copy link
Copy Markdown
ContributorAuthor

Added an integration test for AbstractKVStore and PostgresIntegration test uses it.
Can review it as part of this PR or we can separate it out as well in #5

postgreSQLContainer.getUsername(), postgreSQLContainer.getPassword());
DSLContext dslContext = DSL.using(conn, SQLDialect.POSTGRES);

this.kvStore = new PostgresBackendImpl(dslContext);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

don't we need to close the previous DB connection, otherwise we may run out of file descriptors or such if we have many tests?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Each and every test spins up new db cluster/instance so db connection shouldn't really be a problem.
But I added a AfterEach block to destroy connection in any case.

For production, we are using connection pool and DSL.using(dataSource, dialect) where jooq/pool does the connection management for us.

@G8XSU
G8XSU marked this pull request as ready for review January 26, 2023 01:38

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to get through the tests still

Comment threadapp/build.gradle Outdated
main {
generateSchemaSourceOnCompilation = true

generationTool {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Discussed this offline. Prefer to check in the code but also provide a way for users to generate it at as an option to the build process.


ListKeyVersionsResponse listKeyVersions(ListKeyVersionsRequest request);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: no blanks at end of file here and throughout

@@ -0,0 +1,8 @@
CREATE TABLE vss_db (
store_id character varying(120) NOT NULL,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a convention to have two spaces before NULL / NOT NULL?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

idk, just a copy-paste side-effect from describe table in postgres i guess, will replace with single spaces.

store_id character varying(120) NOT NULL,
key character varying(120) NOT NULL,
value bytea NULL,
version bigint NOT NULL,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was the choice of using a signed integer in the vss.proto based on the fact the database doesn't support unsigned types?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mostly because many languages(kotlin/java/python) don't have good support for unsigned values.
So we avoid using them directly in interface if possible. (had this feedback from cashapp as well)

Comment on lines +49 to +54
dslContext.execute("CREATE TABLE vss_db ("
+ "store_id character varying(120) NOT NULL CHECK (store_id <> ''),"
+ "key character varying(120) NOT NULL,"
+ "value bytea NULL,"
+ "version bigint NOT NULL,"
+ "PRIMARY KEY (store_id, key));");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be possible to take this from the sql file?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that the sql file is present only for documentation purpose and git history.
Its not going to be directly used in db creation, will need to be done manually.
I wanted to avoid a filepath dependency in tests, let me know your thoughts.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could creation be accomplished through a script / program that reads the schema?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

jooq doesn't create table for us and we assume in production that db schema is already created.
In tests however we are creating a fresh instance of db for every test and need to create table/schema everytime.


private void createTable(DSLContext dslContext) {
dslContext.execute("CREATE TABLE vss_db ("
+ "store_id character varying(120) NOT NULL CHECK (store_id <> ''),"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why does this line differ from the sql file?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will fix this.

Comment on lines +53 to +56
} else {
keyValue = KeyValue.newBuilder()
.setKey(request.getKey()).build();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we return an error if there is no record for the key?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think an empty response is preferable in this case.
ResourceNotFound or 404 might represent a myriad of issues and things going wrong. (url wrong etc.)
In this case, we consider it a perfectly valid request to get a key which does not exist or to check existence of a key.
I see no harm in mixing keys that exist with no data and keys which don't exist, to make clients life easier instead of throwing an exception in one case.

Note: This is only applicable if client has permission to storeId, if not then we would want to throw ResourceNotFound.

However, this is a controversial topic and there are reasons to go either way.

Comment on lines +49 to +54
dslContext.execute("CREATE TABLE vss_db ("
+ "store_id character varying(120) NOT NULL CHECK (store_id <> ''),"
+ "key character varying(120) NOT NULL,"
+ "value bytea NULL,"
+ "version bigint NOT NULL,"
+ "PRIMARY KEY (store_id, key));");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could creation be accomplished through a script / program that reads the schema?

KeyValue response = getObject("non_existent_key");

assertThat(response.getKey(), is("non_existent_key"));
assertTrue(response.getValue().isEmpty());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also check that version is empty / zero?

Comment on lines +86 to +94
int[] batchResult = dsl.batch(batchQueries).execute();

for (int numOfRowsUpdated : batchResult) {
if (numOfRowsUpdated == 0) {
throw new ConflictException(
"Transaction could not be completed due to a possible conflict");
}
}
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you test the case where one key failing causes the entire transaction to fail? (i.e., the successful key is not updated)

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like some of the comments for the first commit were resolved in the second commit. You'll want to make sure they are resolved in the right commit so that they are self-contained. Otherwise, looks good and sorry about the delay.

PRIMARY KEY (store_id, key)
);

); No newline at end of file

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add newline.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I earlier got comment about removing newlines/blanks at end of files,
bit confused, let me know if i misunderstood.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, please disregard. I thought that Github was showing the "No newline at end of file" symbol, but I guess I was mistaken.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, i might have fixed it,
So just to clarify there "should" be a newline at EOF?

Addressed other comments as well.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, it should contain a newline, just not an empty line.

@G8XSU
G8XSUforce-pushed the postgres-impl-get-put branch from 344779e to 403b0c2CompareApril 21, 2023 00:03
@G8XSU
G8XSU merged commit 5de859d into lightningdevkit:mainApr 21, 2023
@G8XSUG8XSU mentioned this pull request May 10, 2023
31 tasks
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

@G8XSU@devrandom@jkczyz
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Add initial PostgreSQL implementation for get & put operations by G8XSU · Pull Request #5 · lightningdevkit/vss-server · GitHub
Skip to content

Add initial PostgreSQL implementation for get & put operations - #5

Merged
G8XSU merged 2 commits into
lightningdevkit:mainfrom
G8XSU:postgres-impl-get-put
Apr 21, 2023
Merged

Add initial PostgreSQL implementation for get & put operations#5
G8XSU merged 2 commits into
lightningdevkit:mainfrom
G8XSU:postgres-impl-get-put

Conversation

@G8XSU

@G8XSUG8XSU commented Jan 13, 2023

Copy link
Copy Markdown
Contributor

TestStrategy

How?

  • PostgresIntegrationTest uses testcontainers to spin up docker containers for each test.
  • AbstractKVStoreIntegrationTest defines behavior that every impl of KVStore needs to follow. Different impl's can re-use the same abstract class to test their impl against it.
  • We will keep on adding tests to this as we add more impl details.

@G8XSU
G8XSU requested a review from jkczyzJanuary 13, 2023 01:58
@G8XSUG8XSU changed the title Add basic PostgreSQL implementation for get & put operationsAdd initial PostgreSQL implementation for get & put operationsJan 13, 2023
@G8XSU
G8XSU requested a review from devrandomJanuary 17, 2023 22:36
Comment threadapp/src/main/java/org/vss/impl/postgres/sql/v0_create_vss_db.sql Outdated
Comment threadapp/build.gradle Outdated
main {
generateSchemaSourceOnCompilation = true

generationTool {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we need to make a decision if we check in the generated Java code or not. personally, I'm a bit uncomfortable with generating code on the fly on prod machines, but let's see what other people think.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Discussed this offline. Prefer to check in the code but also provide a way for users to generate it at as an option to the build process.

Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated

VssDbRecord globalVersionRecord = buildVssRecord(storeId,
KeyValue.newBuilder()
.setKey(GLOBAL_VERSION_KEY)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the global version should be stored in a separate table. otherwise, you have to make sure the caller doesn't try to use this key, and it seems messy.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The advantage is that it can be treated as any other keyvalue and easily handled with exactly same cases.

Other consideration is, if we want client to be able to override global_version in certain scenarios. My take is we should allow, end of the day its their storage and versioning, they can do whatever they want with it.

There is also case where client just wants to do a "get" on global_version.
For all purposes, it seems simpler to keep it as normal key-value, otherwise i will need to introduce additional code to support everything.

One case that we will have to handle separately from normal key-value is to not return global_version as part of ListKeyVersions api. (we have dedicated field in response for it)

Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated
Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated
Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated
Comment threadapp/build.gradle Outdated
@devrandom

Copy link
Copy Markdown
Member

also, would be good to have an integration test. not sure if it's better to have it against postgres (more precise model of a production environment) or against a lightweight in-memory SQL DB (faster to run the tests).

.setKey(GLOBAL_VERSION_KEY)
.setVersion(request.getGlobalVersion())
.build());
if (request.hasGlobalVersion()) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this doesn't increment the global version when it's not specified in the request. we always want to increment it, right?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess we could have the specifications say that it doesn't get incremented if not present in the request, but we should be explicit about it, since the developer might not expect that

@G8XSUG8XSUJan 25, 2023

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Based on how optimistic locking works, version needs to be provided by client in order to enact it.
So expectation is that we don't increment it and dont perform the check if developer doesn't supply it.

If global_version is not supplied, it means it is a non-global-version-check-required write.
We shouldn't be incrementing global_version in this case as client-side will not increment and has no way of knowing this without performing a sync.

Based on different application needs, some might not need a global_version check on every write, and this feature is meant to support those applications.

@G8XSU

Copy link
Copy Markdown
ContributorAuthor

Added an integration test for AbstractKVStore and PostgresIntegration test uses it.
Can review it as part of this PR or we can separate it out as well in #5

postgreSQLContainer.getUsername(), postgreSQLContainer.getPassword());
DSLContext dslContext = DSL.using(conn, SQLDialect.POSTGRES);

this.kvStore = new PostgresBackendImpl(dslContext);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

don't we need to close the previous DB connection, otherwise we may run out of file descriptors or such if we have many tests?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Each and every test spins up new db cluster/instance so db connection shouldn't really be a problem.
But I added a AfterEach block to destroy connection in any case.

For production, we are using connection pool and DSL.using(dataSource, dialect) where jooq/pool does the connection management for us.

@G8XSU
G8XSU marked this pull request as ready for review January 26, 2023 01:38

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to get through the tests still

Comment threadapp/build.gradle Outdated
main {
generateSchemaSourceOnCompilation = true

generationTool {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Discussed this offline. Prefer to check in the code but also provide a way for users to generate it at as an option to the build process.


ListKeyVersionsResponse listKeyVersions(ListKeyVersionsRequest request);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: no blanks at end of file here and throughout

@@ -0,0 +1,8 @@
CREATE TABLE vss_db (
store_id character varying(120) NOT NULL,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a convention to have two spaces before NULL / NOT NULL?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

idk, just a copy-paste side-effect from describe table in postgres i guess, will replace with single spaces.

store_id character varying(120) NOT NULL,
key character varying(120) NOT NULL,
value bytea NULL,
version bigint NOT NULL,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was the choice of using a signed integer in the vss.proto based on the fact the database doesn't support unsigned types?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mostly because many languages(kotlin/java/python) don't have good support for unsigned values.
So we avoid using them directly in interface if possible. (had this feedback from cashapp as well)

Comment on lines +49 to +54
dslContext.execute("CREATE TABLE vss_db ("
+ "store_id character varying(120) NOT NULL CHECK (store_id <> ''),"
+ "key character varying(120) NOT NULL,"
+ "value bytea NULL,"
+ "version bigint NOT NULL,"
+ "PRIMARY KEY (store_id, key));");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be possible to take this from the sql file?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that the sql file is present only for documentation purpose and git history.
Its not going to be directly used in db creation, will need to be done manually.
I wanted to avoid a filepath dependency in tests, let me know your thoughts.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could creation be accomplished through a script / program that reads the schema?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

jooq doesn't create table for us and we assume in production that db schema is already created.
In tests however we are creating a fresh instance of db for every test and need to create table/schema everytime.


private void createTable(DSLContext dslContext) {
dslContext.execute("CREATE TABLE vss_db ("
+ "store_id character varying(120) NOT NULL CHECK (store_id <> ''),"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why does this line differ from the sql file?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will fix this.

Comment on lines +53 to +56
} else {
keyValue = KeyValue.newBuilder()
.setKey(request.getKey()).build();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we return an error if there is no record for the key?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think an empty response is preferable in this case.
ResourceNotFound or 404 might represent a myriad of issues and things going wrong. (url wrong etc.)
In this case, we consider it a perfectly valid request to get a key which does not exist or to check existence of a key.
I see no harm in mixing keys that exist with no data and keys which don't exist, to make clients life easier instead of throwing an exception in one case.

Note: This is only applicable if client has permission to storeId, if not then we would want to throw ResourceNotFound.

However, this is a controversial topic and there are reasons to go either way.

Comment on lines +49 to +54
dslContext.execute("CREATE TABLE vss_db ("
+ "store_id character varying(120) NOT NULL CHECK (store_id <> ''),"
+ "key character varying(120) NOT NULL,"
+ "value bytea NULL,"
+ "version bigint NOT NULL,"
+ "PRIMARY KEY (store_id, key));");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could creation be accomplished through a script / program that reads the schema?

KeyValue response = getObject("non_existent_key");

assertThat(response.getKey(), is("non_existent_key"));
assertTrue(response.getValue().isEmpty());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also check that version is empty / zero?

Comment on lines +86 to +94
int[] batchResult = dsl.batch(batchQueries).execute();

for (int numOfRowsUpdated : batchResult) {
if (numOfRowsUpdated == 0) {
throw new ConflictException(
"Transaction could not be completed due to a possible conflict");
}
}
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you test the case where one key failing causes the entire transaction to fail? (i.e., the successful key is not updated)

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like some of the comments for the first commit were resolved in the second commit. You'll want to make sure they are resolved in the right commit so that they are self-contained. Otherwise, looks good and sorry about the delay.

PRIMARY KEY (store_id, key)
);

); No newline at end of file

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add newline.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I earlier got comment about removing newlines/blanks at end of files,
bit confused, let me know if i misunderstood.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, please disregard. I thought that Github was showing the "No newline at end of file" symbol, but I guess I was mistaken.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, i might have fixed it,
So just to clarify there "should" be a newline at EOF?

Addressed other comments as well.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, it should contain a newline, just not an empty line.

@G8XSU
G8XSUforce-pushed the postgres-impl-get-put branch from 344779e to 403b0c2CompareApril 21, 2023 00:03
@G8XSU
G8XSU merged commit 5de859d into lightningdevkit:mainApr 21, 2023
@G8XSUG8XSU mentioned this pull request May 10, 2023
31 tasks
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

@G8XSU@devrandom@jkczyz
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' Add initial PostgreSQL implementation for get & put operations by G8XSU · Pull Request #5 · lightningdevkit/vss-server · GitHub
Skip to content

Add initial PostgreSQL implementation for get & put operations - #5

Merged
G8XSU merged 2 commits into
lightningdevkit:mainfrom
G8XSU:postgres-impl-get-put
Apr 21, 2023
Merged

Add initial PostgreSQL implementation for get & put operations#5
G8XSU merged 2 commits into
lightningdevkit:mainfrom
G8XSU:postgres-impl-get-put

Conversation

@G8XSU

@G8XSUG8XSU commented Jan 13, 2023

Copy link
Copy Markdown
Contributor

TestStrategy

How?

  • PostgresIntegrationTest uses testcontainers to spin up docker containers for each test.
  • AbstractKVStoreIntegrationTest defines behavior that every impl of KVStore needs to follow. Different impl's can re-use the same abstract class to test their impl against it.
  • We will keep on adding tests to this as we add more impl details.

@G8XSU
G8XSU requested a review from jkczyzJanuary 13, 2023 01:58
@G8XSUG8XSU changed the title Add basic PostgreSQL implementation for get & put operationsAdd initial PostgreSQL implementation for get & put operationsJan 13, 2023
@G8XSU
G8XSU requested a review from devrandomJanuary 17, 2023 22:36
Comment threadapp/src/main/java/org/vss/impl/postgres/sql/v0_create_vss_db.sql Outdated
Comment threadapp/build.gradle Outdated
main {
generateSchemaSourceOnCompilation = true

generationTool {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we need to make a decision if we check in the generated Java code or not. personally, I'm a bit uncomfortable with generating code on the fly on prod machines, but let's see what other people think.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Discussed this offline. Prefer to check in the code but also provide a way for users to generate it at as an option to the build process.

Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated

VssDbRecord globalVersionRecord = buildVssRecord(storeId,
KeyValue.newBuilder()
.setKey(GLOBAL_VERSION_KEY)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the global version should be stored in a separate table. otherwise, you have to make sure the caller doesn't try to use this key, and it seems messy.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The advantage is that it can be treated as any other keyvalue and easily handled with exactly same cases.

Other consideration is, if we want client to be able to override global_version in certain scenarios. My take is we should allow, end of the day its their storage and versioning, they can do whatever they want with it.

There is also case where client just wants to do a "get" on global_version.
For all purposes, it seems simpler to keep it as normal key-value, otherwise i will need to introduce additional code to support everything.

One case that we will have to handle separately from normal key-value is to not return global_version as part of ListKeyVersions api. (we have dedicated field in response for it)

Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated
Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated
Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated
Comment threadapp/build.gradle Outdated
@devrandom

Copy link
Copy Markdown
Member

also, would be good to have an integration test. not sure if it's better to have it against postgres (more precise model of a production environment) or against a lightweight in-memory SQL DB (faster to run the tests).

.setKey(GLOBAL_VERSION_KEY)
.setVersion(request.getGlobalVersion())
.build());
if (request.hasGlobalVersion()) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this doesn't increment the global version when it's not specified in the request. we always want to increment it, right?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess we could have the specifications say that it doesn't get incremented if not present in the request, but we should be explicit about it, since the developer might not expect that

@G8XSUG8XSUJan 25, 2023

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Based on how optimistic locking works, version needs to be provided by client in order to enact it.
So expectation is that we don't increment it and dont perform the check if developer doesn't supply it.

If global_version is not supplied, it means it is a non-global-version-check-required write.
We shouldn't be incrementing global_version in this case as client-side will not increment and has no way of knowing this without performing a sync.

Based on different application needs, some might not need a global_version check on every write, and this feature is meant to support those applications.

@G8XSU

Copy link
Copy Markdown
ContributorAuthor

Added an integration test for AbstractKVStore and PostgresIntegration test uses it.
Can review it as part of this PR or we can separate it out as well in #5

postgreSQLContainer.getUsername(), postgreSQLContainer.getPassword());
DSLContext dslContext = DSL.using(conn, SQLDialect.POSTGRES);

this.kvStore = new PostgresBackendImpl(dslContext);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

don't we need to close the previous DB connection, otherwise we may run out of file descriptors or such if we have many tests?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Each and every test spins up new db cluster/instance so db connection shouldn't really be a problem.
But I added a AfterEach block to destroy connection in any case.

For production, we are using connection pool and DSL.using(dataSource, dialect) where jooq/pool does the connection management for us.

@G8XSU
G8XSU marked this pull request as ready for review January 26, 2023 01:38

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to get through the tests still

Comment threadapp/build.gradle Outdated
main {
generateSchemaSourceOnCompilation = true

generationTool {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Discussed this offline. Prefer to check in the code but also provide a way for users to generate it at as an option to the build process.


ListKeyVersionsResponse listKeyVersions(ListKeyVersionsRequest request);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: no blanks at end of file here and throughout

@@ -0,0 +1,8 @@
CREATE TABLE vss_db (
store_id character varying(120) NOT NULL,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a convention to have two spaces before NULL / NOT NULL?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

idk, just a copy-paste side-effect from describe table in postgres i guess, will replace with single spaces.

store_id character varying(120) NOT NULL,
key character varying(120) NOT NULL,
value bytea NULL,
version bigint NOT NULL,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was the choice of using a signed integer in the vss.proto based on the fact the database doesn't support unsigned types?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mostly because many languages(kotlin/java/python) don't have good support for unsigned values.
So we avoid using them directly in interface if possible. (had this feedback from cashapp as well)

Comment on lines +49 to +54
dslContext.execute("CREATE TABLE vss_db ("
+ "store_id character varying(120) NOT NULL CHECK (store_id <> ''),"
+ "key character varying(120) NOT NULL,"
+ "value bytea NULL,"
+ "version bigint NOT NULL,"
+ "PRIMARY KEY (store_id, key));");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be possible to take this from the sql file?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that the sql file is present only for documentation purpose and git history.
Its not going to be directly used in db creation, will need to be done manually.
I wanted to avoid a filepath dependency in tests, let me know your thoughts.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could creation be accomplished through a script / program that reads the schema?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

jooq doesn't create table for us and we assume in production that db schema is already created.
In tests however we are creating a fresh instance of db for every test and need to create table/schema everytime.


private void createTable(DSLContext dslContext) {
dslContext.execute("CREATE TABLE vss_db ("
+ "store_id character varying(120) NOT NULL CHECK (store_id <> ''),"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why does this line differ from the sql file?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will fix this.

Comment on lines +53 to +56
} else {
keyValue = KeyValue.newBuilder()
.setKey(request.getKey()).build();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we return an error if there is no record for the key?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think an empty response is preferable in this case.
ResourceNotFound or 404 might represent a myriad of issues and things going wrong. (url wrong etc.)
In this case, we consider it a perfectly valid request to get a key which does not exist or to check existence of a key.
I see no harm in mixing keys that exist with no data and keys which don't exist, to make clients life easier instead of throwing an exception in one case.

Note: This is only applicable if client has permission to storeId, if not then we would want to throw ResourceNotFound.

However, this is a controversial topic and there are reasons to go either way.

Comment on lines +49 to +54
dslContext.execute("CREATE TABLE vss_db ("
+ "store_id character varying(120) NOT NULL CHECK (store_id <> ''),"
+ "key character varying(120) NOT NULL,"
+ "value bytea NULL,"
+ "version bigint NOT NULL,"
+ "PRIMARY KEY (store_id, key));");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could creation be accomplished through a script / program that reads the schema?

KeyValue response = getObject("non_existent_key");

assertThat(response.getKey(), is("non_existent_key"));
assertTrue(response.getValue().isEmpty());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also check that version is empty / zero?

Comment on lines +86 to +94
int[] batchResult = dsl.batch(batchQueries).execute();

for (int numOfRowsUpdated : batchResult) {
if (numOfRowsUpdated == 0) {
throw new ConflictException(
"Transaction could not be completed due to a possible conflict");
}
}
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you test the case where one key failing causes the entire transaction to fail? (i.e., the successful key is not updated)

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like some of the comments for the first commit were resolved in the second commit. You'll want to make sure they are resolved in the right commit so that they are self-contained. Otherwise, looks good and sorry about the delay.

PRIMARY KEY (store_id, key)
);

); No newline at end of file

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add newline.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I earlier got comment about removing newlines/blanks at end of files,
bit confused, let me know if i misunderstood.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, please disregard. I thought that Github was showing the "No newline at end of file" symbol, but I guess I was mistaken.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, i might have fixed it,
So just to clarify there "should" be a newline at EOF?

Addressed other comments as well.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, it should contain a newline, just not an empty line.

@G8XSU
G8XSUforce-pushed the postgres-impl-get-put branch from 344779e to 403b0c2CompareApril 21, 2023 00:03
@G8XSU
G8XSU merged commit 5de859d into lightningdevkit:mainApr 21, 2023
@G8XSUG8XSU mentioned this pull request May 10, 2023
31 tasks
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

@G8XSU@devrandom@jkczyz
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Add initial PostgreSQL implementation for get & put operations by G8XSU · Pull Request #5 · lightningdevkit/vss-server · GitHub
Skip to content

Add initial PostgreSQL implementation for get & put operations - #5

Merged
G8XSU merged 2 commits into
lightningdevkit:mainfrom
G8XSU:postgres-impl-get-put
Apr 21, 2023
Merged

Add initial PostgreSQL implementation for get & put operations#5
G8XSU merged 2 commits into
lightningdevkit:mainfrom
G8XSU:postgres-impl-get-put

Conversation

@G8XSU

@G8XSUG8XSU commented Jan 13, 2023

Copy link
Copy Markdown
Contributor

TestStrategy

How?

  • PostgresIntegrationTest uses testcontainers to spin up docker containers for each test.
  • AbstractKVStoreIntegrationTest defines behavior that every impl of KVStore needs to follow. Different impl's can re-use the same abstract class to test their impl against it.
  • We will keep on adding tests to this as we add more impl details.

@G8XSU
G8XSU requested a review from jkczyzJanuary 13, 2023 01:58
@G8XSUG8XSU changed the title Add basic PostgreSQL implementation for get & put operationsAdd initial PostgreSQL implementation for get & put operationsJan 13, 2023
@G8XSU
G8XSU requested a review from devrandomJanuary 17, 2023 22:36
Comment threadapp/src/main/java/org/vss/impl/postgres/sql/v0_create_vss_db.sql Outdated
Comment threadapp/build.gradle Outdated
main {
generateSchemaSourceOnCompilation = true

generationTool {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we need to make a decision if we check in the generated Java code or not. personally, I'm a bit uncomfortable with generating code on the fly on prod machines, but let's see what other people think.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Discussed this offline. Prefer to check in the code but also provide a way for users to generate it at as an option to the build process.

Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated

VssDbRecord globalVersionRecord = buildVssRecord(storeId,
KeyValue.newBuilder()
.setKey(GLOBAL_VERSION_KEY)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the global version should be stored in a separate table. otherwise, you have to make sure the caller doesn't try to use this key, and it seems messy.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The advantage is that it can be treated as any other keyvalue and easily handled with exactly same cases.

Other consideration is, if we want client to be able to override global_version in certain scenarios. My take is we should allow, end of the day its their storage and versioning, they can do whatever they want with it.

There is also case where client just wants to do a "get" on global_version.
For all purposes, it seems simpler to keep it as normal key-value, otherwise i will need to introduce additional code to support everything.

One case that we will have to handle separately from normal key-value is to not return global_version as part of ListKeyVersions api. (we have dedicated field in response for it)

Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated
Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated
Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated
Comment threadapp/build.gradle Outdated
@devrandom

Copy link
Copy Markdown
Member

also, would be good to have an integration test. not sure if it's better to have it against postgres (more precise model of a production environment) or against a lightweight in-memory SQL DB (faster to run the tests).

.setKey(GLOBAL_VERSION_KEY)
.setVersion(request.getGlobalVersion())
.build());
if (request.hasGlobalVersion()) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this doesn't increment the global version when it's not specified in the request. we always want to increment it, right?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess we could have the specifications say that it doesn't get incremented if not present in the request, but we should be explicit about it, since the developer might not expect that

@G8XSUG8XSUJan 25, 2023

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Based on how optimistic locking works, version needs to be provided by client in order to enact it.
So expectation is that we don't increment it and dont perform the check if developer doesn't supply it.

If global_version is not supplied, it means it is a non-global-version-check-required write.
We shouldn't be incrementing global_version in this case as client-side will not increment and has no way of knowing this without performing a sync.

Based on different application needs, some might not need a global_version check on every write, and this feature is meant to support those applications.

@G8XSU

Copy link
Copy Markdown
ContributorAuthor

Added an integration test for AbstractKVStore and PostgresIntegration test uses it.
Can review it as part of this PR or we can separate it out as well in #5

postgreSQLContainer.getUsername(), postgreSQLContainer.getPassword());
DSLContext dslContext = DSL.using(conn, SQLDialect.POSTGRES);

this.kvStore = new PostgresBackendImpl(dslContext);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

don't we need to close the previous DB connection, otherwise we may run out of file descriptors or such if we have many tests?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Each and every test spins up new db cluster/instance so db connection shouldn't really be a problem.
But I added a AfterEach block to destroy connection in any case.

For production, we are using connection pool and DSL.using(dataSource, dialect) where jooq/pool does the connection management for us.

@G8XSU
G8XSU marked this pull request as ready for review January 26, 2023 01:38

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to get through the tests still

Comment threadapp/build.gradle Outdated
main {
generateSchemaSourceOnCompilation = true

generationTool {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Discussed this offline. Prefer to check in the code but also provide a way for users to generate it at as an option to the build process.


ListKeyVersionsResponse listKeyVersions(ListKeyVersionsRequest request);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: no blanks at end of file here and throughout

@@ -0,0 +1,8 @@
CREATE TABLE vss_db (
store_id character varying(120) NOT NULL,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a convention to have two spaces before NULL / NOT NULL?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

idk, just a copy-paste side-effect from describe table in postgres i guess, will replace with single spaces.

store_id character varying(120) NOT NULL,
key character varying(120) NOT NULL,
value bytea NULL,
version bigint NOT NULL,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was the choice of using a signed integer in the vss.proto based on the fact the database doesn't support unsigned types?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mostly because many languages(kotlin/java/python) don't have good support for unsigned values.
So we avoid using them directly in interface if possible. (had this feedback from cashapp as well)

Comment on lines +49 to +54
dslContext.execute("CREATE TABLE vss_db ("
+ "store_id character varying(120) NOT NULL CHECK (store_id <> ''),"
+ "key character varying(120) NOT NULL,"
+ "value bytea NULL,"
+ "version bigint NOT NULL,"
+ "PRIMARY KEY (store_id, key));");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be possible to take this from the sql file?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that the sql file is present only for documentation purpose and git history.
Its not going to be directly used in db creation, will need to be done manually.
I wanted to avoid a filepath dependency in tests, let me know your thoughts.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could creation be accomplished through a script / program that reads the schema?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

jooq doesn't create table for us and we assume in production that db schema is already created.
In tests however we are creating a fresh instance of db for every test and need to create table/schema everytime.


private void createTable(DSLContext dslContext) {
dslContext.execute("CREATE TABLE vss_db ("
+ "store_id character varying(120) NOT NULL CHECK (store_id <> ''),"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why does this line differ from the sql file?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will fix this.

Comment on lines +53 to +56
} else {
keyValue = KeyValue.newBuilder()
.setKey(request.getKey()).build();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we return an error if there is no record for the key?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think an empty response is preferable in this case.
ResourceNotFound or 404 might represent a myriad of issues and things going wrong. (url wrong etc.)
In this case, we consider it a perfectly valid request to get a key which does not exist or to check existence of a key.
I see no harm in mixing keys that exist with no data and keys which don't exist, to make clients life easier instead of throwing an exception in one case.

Note: This is only applicable if client has permission to storeId, if not then we would want to throw ResourceNotFound.

However, this is a controversial topic and there are reasons to go either way.

Comment on lines +49 to +54
dslContext.execute("CREATE TABLE vss_db ("
+ "store_id character varying(120) NOT NULL CHECK (store_id <> ''),"
+ "key character varying(120) NOT NULL,"
+ "value bytea NULL,"
+ "version bigint NOT NULL,"
+ "PRIMARY KEY (store_id, key));");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could creation be accomplished through a script / program that reads the schema?

KeyValue response = getObject("non_existent_key");

assertThat(response.getKey(), is("non_existent_key"));
assertTrue(response.getValue().isEmpty());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also check that version is empty / zero?

Comment on lines +86 to +94
int[] batchResult = dsl.batch(batchQueries).execute();

for (int numOfRowsUpdated : batchResult) {
if (numOfRowsUpdated == 0) {
throw new ConflictException(
"Transaction could not be completed due to a possible conflict");
}
}
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you test the case where one key failing causes the entire transaction to fail? (i.e., the successful key is not updated)

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like some of the comments for the first commit were resolved in the second commit. You'll want to make sure they are resolved in the right commit so that they are self-contained. Otherwise, looks good and sorry about the delay.

PRIMARY KEY (store_id, key)
);

); No newline at end of file

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add newline.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I earlier got comment about removing newlines/blanks at end of files,
bit confused, let me know if i misunderstood.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, please disregard. I thought that Github was showing the "No newline at end of file" symbol, but I guess I was mistaken.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, i might have fixed it,
So just to clarify there "should" be a newline at EOF?

Addressed other comments as well.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, it should contain a newline, just not an empty line.

@G8XSU
G8XSUforce-pushed the postgres-impl-get-put branch from 344779e to 403b0c2CompareApril 21, 2023 00:03
@G8XSU
G8XSU merged commit 5de859d into lightningdevkit:mainApr 21, 2023
@G8XSUG8XSU mentioned this pull request May 10, 2023
31 tasks
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

@G8XSU@devrandom@jkczyz
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Add initial PostgreSQL implementation for get & put operations by G8XSU · Pull Request #5 · lightningdevkit/vss-server · GitHub
Skip to content

Add initial PostgreSQL implementation for get & put operations - #5

Merged
G8XSU merged 2 commits into
lightningdevkit:mainfrom
G8XSU:postgres-impl-get-put
Apr 21, 2023
Merged

Add initial PostgreSQL implementation for get & put operations#5
G8XSU merged 2 commits into
lightningdevkit:mainfrom
G8XSU:postgres-impl-get-put

Conversation

@G8XSU

@G8XSUG8XSU commented Jan 13, 2023

Copy link
Copy Markdown
Contributor

TestStrategy

How?

  • PostgresIntegrationTest uses testcontainers to spin up docker containers for each test.
  • AbstractKVStoreIntegrationTest defines behavior that every impl of KVStore needs to follow. Different impl's can re-use the same abstract class to test their impl against it.
  • We will keep on adding tests to this as we add more impl details.

@G8XSU
G8XSU requested a review from jkczyzJanuary 13, 2023 01:58
@G8XSUG8XSU changed the title Add basic PostgreSQL implementation for get & put operationsAdd initial PostgreSQL implementation for get & put operationsJan 13, 2023
@G8XSU
G8XSU requested a review from devrandomJanuary 17, 2023 22:36
Comment threadapp/src/main/java/org/vss/impl/postgres/sql/v0_create_vss_db.sql Outdated
Comment threadapp/build.gradle Outdated
main {
generateSchemaSourceOnCompilation = true

generationTool {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we need to make a decision if we check in the generated Java code or not. personally, I'm a bit uncomfortable with generating code on the fly on prod machines, but let's see what other people think.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Discussed this offline. Prefer to check in the code but also provide a way for users to generate it at as an option to the build process.

Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated

VssDbRecord globalVersionRecord = buildVssRecord(storeId,
KeyValue.newBuilder()
.setKey(GLOBAL_VERSION_KEY)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the global version should be stored in a separate table. otherwise, you have to make sure the caller doesn't try to use this key, and it seems messy.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The advantage is that it can be treated as any other keyvalue and easily handled with exactly same cases.

Other consideration is, if we want client to be able to override global_version in certain scenarios. My take is we should allow, end of the day its their storage and versioning, they can do whatever they want with it.

There is also case where client just wants to do a "get" on global_version.
For all purposes, it seems simpler to keep it as normal key-value, otherwise i will need to introduce additional code to support everything.

One case that we will have to handle separately from normal key-value is to not return global_version as part of ListKeyVersions api. (we have dedicated field in response for it)

Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated
Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated
Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated
Comment threadapp/build.gradle Outdated
@devrandom

Copy link
Copy Markdown
Member

also, would be good to have an integration test. not sure if it's better to have it against postgres (more precise model of a production environment) or against a lightweight in-memory SQL DB (faster to run the tests).

.setKey(GLOBAL_VERSION_KEY)
.setVersion(request.getGlobalVersion())
.build());
if (request.hasGlobalVersion()) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this doesn't increment the global version when it's not specified in the request. we always want to increment it, right?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess we could have the specifications say that it doesn't get incremented if not present in the request, but we should be explicit about it, since the developer might not expect that

@G8XSUG8XSUJan 25, 2023

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Based on how optimistic locking works, version needs to be provided by client in order to enact it.
So expectation is that we don't increment it and dont perform the check if developer doesn't supply it.

If global_version is not supplied, it means it is a non-global-version-check-required write.
We shouldn't be incrementing global_version in this case as client-side will not increment and has no way of knowing this without performing a sync.

Based on different application needs, some might not need a global_version check on every write, and this feature is meant to support those applications.

@G8XSU

Copy link
Copy Markdown
ContributorAuthor

Added an integration test for AbstractKVStore and PostgresIntegration test uses it.
Can review it as part of this PR or we can separate it out as well in #5

postgreSQLContainer.getUsername(), postgreSQLContainer.getPassword());
DSLContext dslContext = DSL.using(conn, SQLDialect.POSTGRES);

this.kvStore = new PostgresBackendImpl(dslContext);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

don't we need to close the previous DB connection, otherwise we may run out of file descriptors or such if we have many tests?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Each and every test spins up new db cluster/instance so db connection shouldn't really be a problem.
But I added a AfterEach block to destroy connection in any case.

For production, we are using connection pool and DSL.using(dataSource, dialect) where jooq/pool does the connection management for us.

@G8XSU
G8XSU marked this pull request as ready for review January 26, 2023 01:38

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to get through the tests still

Comment threadapp/build.gradle Outdated
main {
generateSchemaSourceOnCompilation = true

generationTool {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Discussed this offline. Prefer to check in the code but also provide a way for users to generate it at as an option to the build process.


ListKeyVersionsResponse listKeyVersions(ListKeyVersionsRequest request);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: no blanks at end of file here and throughout

@@ -0,0 +1,8 @@
CREATE TABLE vss_db (
store_id character varying(120) NOT NULL,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a convention to have two spaces before NULL / NOT NULL?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

idk, just a copy-paste side-effect from describe table in postgres i guess, will replace with single spaces.

store_id character varying(120) NOT NULL,
key character varying(120) NOT NULL,
value bytea NULL,
version bigint NOT NULL,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was the choice of using a signed integer in the vss.proto based on the fact the database doesn't support unsigned types?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mostly because many languages(kotlin/java/python) don't have good support for unsigned values.
So we avoid using them directly in interface if possible. (had this feedback from cashapp as well)

Comment on lines +49 to +54
dslContext.execute("CREATE TABLE vss_db ("
+ "store_id character varying(120) NOT NULL CHECK (store_id <> ''),"
+ "key character varying(120) NOT NULL,"
+ "value bytea NULL,"
+ "version bigint NOT NULL,"
+ "PRIMARY KEY (store_id, key));");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be possible to take this from the sql file?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that the sql file is present only for documentation purpose and git history.
Its not going to be directly used in db creation, will need to be done manually.
I wanted to avoid a filepath dependency in tests, let me know your thoughts.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could creation be accomplished through a script / program that reads the schema?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

jooq doesn't create table for us and we assume in production that db schema is already created.
In tests however we are creating a fresh instance of db for every test and need to create table/schema everytime.


private void createTable(DSLContext dslContext) {
dslContext.execute("CREATE TABLE vss_db ("
+ "store_id character varying(120) NOT NULL CHECK (store_id <> ''),"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why does this line differ from the sql file?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will fix this.

Comment on lines +53 to +56
} else {
keyValue = KeyValue.newBuilder()
.setKey(request.getKey()).build();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we return an error if there is no record for the key?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think an empty response is preferable in this case.
ResourceNotFound or 404 might represent a myriad of issues and things going wrong. (url wrong etc.)
In this case, we consider it a perfectly valid request to get a key which does not exist or to check existence of a key.
I see no harm in mixing keys that exist with no data and keys which don't exist, to make clients life easier instead of throwing an exception in one case.

Note: This is only applicable if client has permission to storeId, if not then we would want to throw ResourceNotFound.

However, this is a controversial topic and there are reasons to go either way.

Comment on lines +49 to +54
dslContext.execute("CREATE TABLE vss_db ("
+ "store_id character varying(120) NOT NULL CHECK (store_id <> ''),"
+ "key character varying(120) NOT NULL,"
+ "value bytea NULL,"
+ "version bigint NOT NULL,"
+ "PRIMARY KEY (store_id, key));");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could creation be accomplished through a script / program that reads the schema?

KeyValue response = getObject("non_existent_key");

assertThat(response.getKey(), is("non_existent_key"));
assertTrue(response.getValue().isEmpty());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also check that version is empty / zero?

Comment on lines +86 to +94
int[] batchResult = dsl.batch(batchQueries).execute();

for (int numOfRowsUpdated : batchResult) {
if (numOfRowsUpdated == 0) {
throw new ConflictException(
"Transaction could not be completed due to a possible conflict");
}
}
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you test the case where one key failing causes the entire transaction to fail? (i.e., the successful key is not updated)

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like some of the comments for the first commit were resolved in the second commit. You'll want to make sure they are resolved in the right commit so that they are self-contained. Otherwise, looks good and sorry about the delay.

PRIMARY KEY (store_id, key)
);

); No newline at end of file

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add newline.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I earlier got comment about removing newlines/blanks at end of files,
bit confused, let me know if i misunderstood.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, please disregard. I thought that Github was showing the "No newline at end of file" symbol, but I guess I was mistaken.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, i might have fixed it,
So just to clarify there "should" be a newline at EOF?

Addressed other comments as well.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, it should contain a newline, just not an empty line.

@G8XSU
G8XSUforce-pushed the postgres-impl-get-put branch from 344779e to 403b0c2CompareApril 21, 2023 00:03
@G8XSU
G8XSU merged commit 5de859d into lightningdevkit:mainApr 21, 2023
@G8XSUG8XSU mentioned this pull request May 10, 2023
31 tasks
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

@G8XSU@devrandom@jkczyz
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); Add initial PostgreSQL implementation for get & put operations by G8XSU · Pull Request #5 · lightningdevkit/vss-server · GitHub
Skip to content

Add initial PostgreSQL implementation for get & put operations - #5

Merged
G8XSU merged 2 commits into
lightningdevkit:mainfrom
G8XSU:postgres-impl-get-put
Apr 21, 2023
Merged

Add initial PostgreSQL implementation for get & put operations#5
G8XSU merged 2 commits into
lightningdevkit:mainfrom
G8XSU:postgres-impl-get-put

Conversation

@G8XSU

@G8XSUG8XSU commented Jan 13, 2023

Copy link
Copy Markdown
Contributor

TestStrategy

How?

  • PostgresIntegrationTest uses testcontainers to spin up docker containers for each test.
  • AbstractKVStoreIntegrationTest defines behavior that every impl of KVStore needs to follow. Different impl's can re-use the same abstract class to test their impl against it.
  • We will keep on adding tests to this as we add more impl details.

@G8XSU
G8XSU requested a review from jkczyzJanuary 13, 2023 01:58
@G8XSUG8XSU changed the title Add basic PostgreSQL implementation for get & put operationsAdd initial PostgreSQL implementation for get & put operationsJan 13, 2023
@G8XSU
G8XSU requested a review from devrandomJanuary 17, 2023 22:36
Comment threadapp/src/main/java/org/vss/impl/postgres/sql/v0_create_vss_db.sql Outdated
Comment threadapp/build.gradle Outdated
main {
generateSchemaSourceOnCompilation = true

generationTool {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we need to make a decision if we check in the generated Java code or not. personally, I'm a bit uncomfortable with generating code on the fly on prod machines, but let's see what other people think.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Discussed this offline. Prefer to check in the code but also provide a way for users to generate it at as an option to the build process.

Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated

VssDbRecord globalVersionRecord = buildVssRecord(storeId,
KeyValue.newBuilder()
.setKey(GLOBAL_VERSION_KEY)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the global version should be stored in a separate table. otherwise, you have to make sure the caller doesn't try to use this key, and it seems messy.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The advantage is that it can be treated as any other keyvalue and easily handled with exactly same cases.

Other consideration is, if we want client to be able to override global_version in certain scenarios. My take is we should allow, end of the day its their storage and versioning, they can do whatever they want with it.

There is also case where client just wants to do a "get" on global_version.
For all purposes, it seems simpler to keep it as normal key-value, otherwise i will need to introduce additional code to support everything.

One case that we will have to handle separately from normal key-value is to not return global_version as part of ListKeyVersions api. (we have dedicated field in response for it)

Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated
Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated
Comment threadapp/src/main/java/org/vss/impl/postgres/PostgresBackendImpl.java Outdated
Comment threadapp/build.gradle Outdated
@devrandom

Copy link
Copy Markdown
Member

also, would be good to have an integration test. not sure if it's better to have it against postgres (more precise model of a production environment) or against a lightweight in-memory SQL DB (faster to run the tests).

.setKey(GLOBAL_VERSION_KEY)
.setVersion(request.getGlobalVersion())
.build());
if (request.hasGlobalVersion()) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this doesn't increment the global version when it's not specified in the request. we always want to increment it, right?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess we could have the specifications say that it doesn't get incremented if not present in the request, but we should be explicit about it, since the developer might not expect that

@G8XSUG8XSUJan 25, 2023

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Based on how optimistic locking works, version needs to be provided by client in order to enact it.
So expectation is that we don't increment it and dont perform the check if developer doesn't supply it.

If global_version is not supplied, it means it is a non-global-version-check-required write.
We shouldn't be incrementing global_version in this case as client-side will not increment and has no way of knowing this without performing a sync.

Based on different application needs, some might not need a global_version check on every write, and this feature is meant to support those applications.

@G8XSU

Copy link
Copy Markdown
ContributorAuthor

Added an integration test for AbstractKVStore and PostgresIntegration test uses it.
Can review it as part of this PR or we can separate it out as well in #5

postgreSQLContainer.getUsername(), postgreSQLContainer.getPassword());
DSLContext dslContext = DSL.using(conn, SQLDialect.POSTGRES);

this.kvStore = new PostgresBackendImpl(dslContext);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

don't we need to close the previous DB connection, otherwise we may run out of file descriptors or such if we have many tests?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Each and every test spins up new db cluster/instance so db connection shouldn't really be a problem.
But I added a AfterEach block to destroy connection in any case.

For production, we are using connection pool and DSL.using(dataSource, dialect) where jooq/pool does the connection management for us.

@G8XSU
G8XSU marked this pull request as ready for review January 26, 2023 01:38

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to get through the tests still

Comment threadapp/build.gradle Outdated
main {
generateSchemaSourceOnCompilation = true

generationTool {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Discussed this offline. Prefer to check in the code but also provide a way for users to generate it at as an option to the build process.


ListKeyVersionsResponse listKeyVersions(ListKeyVersionsRequest request);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: no blanks at end of file here and throughout

@@ -0,0 +1,8 @@
CREATE TABLE vss_db (
store_id character varying(120) NOT NULL,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a convention to have two spaces before NULL / NOT NULL?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

idk, just a copy-paste side-effect from describe table in postgres i guess, will replace with single spaces.

store_id character varying(120) NOT NULL,
key character varying(120) NOT NULL,
value bytea NULL,
version bigint NOT NULL,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was the choice of using a signed integer in the vss.proto based on the fact the database doesn't support unsigned types?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mostly because many languages(kotlin/java/python) don't have good support for unsigned values.
So we avoid using them directly in interface if possible. (had this feedback from cashapp as well)

Comment on lines +49 to +54
dslContext.execute("CREATE TABLE vss_db ("
+ "store_id character varying(120) NOT NULL CHECK (store_id <> ''),"
+ "key character varying(120) NOT NULL,"
+ "value bytea NULL,"
+ "version bigint NOT NULL,"
+ "PRIMARY KEY (store_id, key));");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be possible to take this from the sql file?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that the sql file is present only for documentation purpose and git history.
Its not going to be directly used in db creation, will need to be done manually.
I wanted to avoid a filepath dependency in tests, let me know your thoughts.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could creation be accomplished through a script / program that reads the schema?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

jooq doesn't create table for us and we assume in production that db schema is already created.
In tests however we are creating a fresh instance of db for every test and need to create table/schema everytime.


private void createTable(DSLContext dslContext) {
dslContext.execute("CREATE TABLE vss_db ("
+ "store_id character varying(120) NOT NULL CHECK (store_id <> ''),"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why does this line differ from the sql file?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will fix this.

Comment on lines +53 to +56
} else {
keyValue = KeyValue.newBuilder()
.setKey(request.getKey()).build();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we return an error if there is no record for the key?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think an empty response is preferable in this case.
ResourceNotFound or 404 might represent a myriad of issues and things going wrong. (url wrong etc.)
In this case, we consider it a perfectly valid request to get a key which does not exist or to check existence of a key.
I see no harm in mixing keys that exist with no data and keys which don't exist, to make clients life easier instead of throwing an exception in one case.

Note: This is only applicable if client has permission to storeId, if not then we would want to throw ResourceNotFound.

However, this is a controversial topic and there are reasons to go either way.

Comment on lines +49 to +54
dslContext.execute("CREATE TABLE vss_db ("
+ "store_id character varying(120) NOT NULL CHECK (store_id <> ''),"
+ "key character varying(120) NOT NULL,"
+ "value bytea NULL,"
+ "version bigint NOT NULL,"
+ "PRIMARY KEY (store_id, key));");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could creation be accomplished through a script / program that reads the schema?

KeyValue response = getObject("non_existent_key");

assertThat(response.getKey(), is("non_existent_key"));
assertTrue(response.getValue().isEmpty());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also check that version is empty / zero?

Comment on lines +86 to +94
int[] batchResult = dsl.batch(batchQueries).execute();

for (int numOfRowsUpdated : batchResult) {
if (numOfRowsUpdated == 0) {
throw new ConflictException(
"Transaction could not be completed due to a possible conflict");
}
}
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you test the case where one key failing causes the entire transaction to fail? (i.e., the successful key is not updated)

@jkczyzjkczyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like some of the comments for the first commit were resolved in the second commit. You'll want to make sure they are resolved in the right commit so that they are self-contained. Otherwise, looks good and sorry about the delay.

PRIMARY KEY (store_id, key)
);

); No newline at end of file

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add newline.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I earlier got comment about removing newlines/blanks at end of files,
bit confused, let me know if i misunderstood.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, please disregard. I thought that Github was showing the "No newline at end of file" symbol, but I guess I was mistaken.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, i might have fixed it,
So just to clarify there "should" be a newline at EOF?

Addressed other comments as well.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, it should contain a newline, just not an empty line.

@G8XSU
G8XSUforce-pushed the postgres-impl-get-put branch from 344779e to 403b0c2CompareApril 21, 2023 00:03
@G8XSU
G8XSU merged commit 5de859d into lightningdevkit:mainApr 21, 2023
@G8XSUG8XSU mentioned this pull request May 10, 2023
31 tasks
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

@G8XSU@devrandom@jkczyz