★ wanayoo — archive 1999 https://github.com/commercetools/commercetools-sync-java/issues/336Nouvelle recherche | Portail wanayoo
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow getting information about successful synchronization right after it is done, not after whole batch was processed #336

Open
jarzynp opened this issue Nov 21, 2018 · 14 comments

Comments

@jarzynp
Copy link
Contributor

@jarzynp jarzynp commented Nov 21, 2018

Description

We need to gather data about sync process (for reporting purposes):

  • which data was synchronized
  • what kind of operations were done (what was added, removed or updated)

Current Behaviour

There are only statistics available: how many was processed, created, updated and failed without no detailed informations which is not enough.

Possible Solution

This functionality can be obtained by extending BaseSyncOptions class and adding callback methods which will be called after finish processing item.

Will come with PR.

jarzynp pushed a commit to ambsoft/commercetools-sync-java that referenced this issue Nov 22, 2018
@heshamMassoud
Copy link
Contributor

@heshamMassoud heshamMassoud commented Nov 22, 2018

Hi @jarzynp,

Thanks for showing interest in the library and creating the feature request.

Could you please explain the exact use case or benefit of such feature? :)

What is exactly meant by "reporting purposes" and "which data was synchronized"
"what kind of operations were done"?

Maybe describing how does the output of the logic you require look like could make the use case more clearer.

@jarzynp
Copy link
Contributor Author

@jarzynp jarzynp commented Nov 22, 2018

Hi @heshamMassoud

We were talking about this on our workshop last week in Berlin in Commercetools office.
By we I mean: You, Pablo (from Commercetools side), Waldek and me (from AMB side).

Reporting purposes (after sync is finished) - gather and prepare report which will contain informations something like (it is not yet decided how will it look like, this is only a draft I came with):

  • ProductType1 was synchronized, operations:
    a) name was changed to "new name"
    b) attribute1 was removed
    c) attribute2 was changed to "new attribute value"
    d) "new enum value" was added to attribute3
  • ProductType2 - no changes

PR is prepared: #337

@heshamMassoud
Copy link
Contributor

@heshamMassoud heshamMassoud commented Nov 22, 2018

Yes, I remember us discussing this case. But we just wanted to know more information about the use case. Just in case it could be achieved otherwise. Also to make sure the desired workflow has the correct pattern :)

As a follow up question, How is this result meant to be used? is it meant to be used in an automated programmatic way that reacts to such granular changes after they had happened or is someone actually manually reading such reports? (maybe @JoergKa and/or @pablotto can add their input on this too.)

From previous experience we know that such reports when frequent might sometimes be rendered as not useful but more as noise. (cc: @butenkor)

@jarzynp
Copy link
Contributor Author

@jarzynp jarzynp commented Nov 22, 2018

If I remember correctly, at first they will be written to a file, but final solution is to write them to elasticsearch.

But you're right - best to ask Pablo, unless Waldek remembers more.

@pablo-ct
Copy link

@pablo-ct pablo-ct commented Nov 22, 2018

Hi @jarzynp ,

the best person that can answer to this question is your PO or the Stakeholder himself. Please contact him to define exactly what kind of information he/she expects from this report.

Email, file or a fancy dashboard on top of elastic search are just the mediums how this report will be provided/presented to the end user and probably you will start with something easy that it will change over time.

As this information is primally going to be used as a report, I can imagine the information will be summarised in some way (counters for example) in most cases. On the other hand extended details could be useful to create a history of changes over time.

@heshamMassoud about your question regarding the automated or manual use of this information. For the beginning just "manual" as it is just a report, but in the future... who knows? maybe we want to react on some events on this report too. (I can imagine some of our services would be happy to know about changes in the product-model because they maintain white/black list of attributes for example)

@jarzynp about the structure/model of the applied changes, please consider a standard like JSONPatch. I'm not sure if the CTP data model is suitable for it directly, as I think there is no guarantee on the order in which AttributeDefinition objects in the attributes array of the ProductType are returned each time (but you could do something similar by transforming the CTP data model from an array of attributes to an attributes object).

@valdemon
Copy link

@valdemon valdemon commented Nov 22, 2018

@pablotto +1 for JSONPatch - that was my first association when reading https://docs.commercetools.com/http-api.html#partial-updates - would be straight forward if used there.. But we can make an attempt to translate actions into this standard for reporting / eventing purpose in our planned service.
I agree the report structure/model is the main concern here. The medium is just an agreement for the first iteration, it's comparably easy to use either a file appender or eg. consume a docker console output via logspout-logstash to ELK.

@heshamMassoud as far as I understood there is a requirement to report details about synchronization in the first iteration of our task (means what exactly has changed on targets after sync + what has failed), regardless of its further processing. The use case can be a detailed reporting for the Configuration Manager (person) maintaining the Master Configuration Project (in our task semantic the reference project being a source of truth from where the data should be synced to a particular set of projects).

@MelNiermann
Copy link

@MelNiermann MelNiermann commented Nov 23, 2018 •

@heshamMassoud
cc: @valdemon & @pablotto

In our project every partner has his own project. Currently we have a lot different partners (increasing constantly) with one project for staging and one for production, which we have to maintain.

The goal is, that the product type configuration (and all other configs as well - like line item states, taxes, custom objects) are the same in every project.
On a nearly daily basis we have to change some of the configuration, because of new features, new attributes or enum values - this includes update, create and delete actions.

If we change something and synchronize this to all projects, we have to know, whether these action's where successful or not for every project.

All the changes have to be communicated to all partners. Before we are doing this we have to make sure, that everything will be okay and is ready to use. In case of failed sync actions, we have to check manually why something went wrong (e.g. enum value is still in use), to be able to correct it.
Therefore we need to log every action with the state of success.

Cheers
Mel

@heshamMassoud
Copy link
Contributor

@heshamMassoud heshamMassoud commented Nov 23, 2018

Hi @MelNiermann @valdemon

Thanks for your input. From what I understand from your comment, is that what is important for you is to know whether something has went wrong during the sync process and details about what exactly went wrong so that it can be fixed. But not exactly went successful.

And this can already be achieved using the errorCallback and warningCallback when configuring your sync instance options. For example, you can log any warning or error event as follows:

final Logger logger = LoggerFactory.getLogger(MySync.class);
final ProductSyncOptions productsyncOptions = ProductSyncOptionsBuilder.of(sphereClient)
                                                       .errorCallback((errorMessage, exception) -> {
                                                           LOGGER.error(errorMessage, exception);
                                                       })
                                                       .warningCallback(warningMessage -> {
                                                           LOGGER.warn(warningMessage);
                                                       })
                                                                       .build();

Logging is just one simple use case. But you can put any logic you desire in the callbacks using the errorMessage and the exception which could contain sth like:

Failed to create draft with key: '1'. Reason: io.sphere.sdk.client.ErrorResponseException: detailMessage: Invalid key '1'. Keys may only contain alphanumeric characters, underscores and hyphens and must have a minimum length of 2 characters and maximum length of 256 characters.
      summary: POST https://api.sphere.io/demo-project/categories failed  with response code 400 with X-Correlation-ID `demo-project/6ec82f80-c414-4e5c-a42a-e85df4b31766` on 2018-09-04T09:14:17.140Z
      http response formatted body: {
        "statusCode" : 400,
        "message" : "Invalid key '1'. Keys may only contain alphanumeric characters, underscores and hyphens and must have a minimum length of 2 characters and maximum length of 256 characters.",
        "errors" : [ {
          "code" : "InvalidInput",
          "message" : "Invalid key '1'. Keys may only contain alphanumeric characters, underscores and hyphens and must have a minimum length of 2 characters and maximum length of 256 characters."
        } ]
      .....

So this gives you more context/info about the error that had happened. We have also a new feature to improve this errorCallback, which will come in the release after the next, where you get more information with the callback e.g. the actual resource object that had failed, which could give you more flexibility to extract only the information about that resource that failed (e.g. key or maybe a custom field, etc..)

That's other than the fact that in the end of the sync process you also get statistics which contains a summary of what had happened that looks as follows:

{
  "reportMessage": "Summary: 510 categories were processed in total (0 created, 485 updated, 10 failed to sync and 0 categories with a missing parent).",
  "totalUpdated": 485,
  "totalCreated": 0,
  "totalFailed": 10,
  "totalProcessed": 510,....
}

Do you think the aforementioned features would suffice for your use case? or did I misunderstand something?

@valdemon
Copy link

@valdemon valdemon commented Nov 26, 2018

Hi @heshamMassoud I guess @MelNiermann will finally respond here whether the reporting level of details being only a summary and details concerning only errors and warnings (as presented above) is enough from the business perspective.
In such a case we can close (archive ;) ) this PR for eventual future use, when eg. detailed change event log envisioned above by @pablotto would start to be required.

Concerning the error / warning callbacks - it feels like the #107 would be welcome to have it done.
Also would be even more cool when the callback Exception (currently Throwable) would become some specified type, having some update/create action context related attribute and a structured/parseable (JSON?) message (especially that the excepion parameter of the errorCallback appears to be optional).

Could you please also put some light on warnings? What are example situations when warnings are raised?

@jarzynp
Copy link
Contributor Author

@jarzynp jarzynp commented Nov 27, 2018

Hi all,

Warnings are raised during preparation phase: while we are retrieving data to be synchronized and something is not fully right with them (but probably it is not crucial for sync process to continue) or while preparing update actions.
Example situation for ProductType: ProductType with id: '%s' has no key set. Keys are required for productType matching.
If I understand this correctly in case of warning it is not preventing item from being synced but it may prevent its full synchronization. @heshamMassoud can you confirm/correct me if I'm wrong?

Another thing is #107: when error occur:

  • in case of creating - it is obvious it couldn't be created so it has to be fixed manually
  • in case of updating - I agree with @valdemon, it would be good to have context (failing UpdateAction maybe?)
@jarzynp
Copy link
Contributor Author

@jarzynp jarzynp commented Nov 28, 2018

After some more digging - almost each of exceptions are extending SphereException and it contains response (body and headers) and request as SphereRequest which contains actions. The problem is we only don't know which action failed.

Example of response body in case when request is wrong:

{
  "statusCode" : 400,
  "message" : "Request body does not contain valid JSON.",
  "errors" : [ {
    "code" : "InvalidJsonInput",
    "message" : "Request body does not contain valid JSON.",
    "detailedErrorMessage" : "actions -> name: Missing required value"
  }, {
    "code" : "InvalidJsonInput",
    "message" : "Request body does not contain valid JSON.",
    "detailedErrorMessage" : "actions -> attributes -> type: Missing required value"
  } ]
}
@heshamMassoud
Copy link
Contributor

@heshamMassoud heshamMassoud commented Nov 29, 2018

@valdemon

Hi @heshamMassoud I guess @MelNiermann will finally respond here whether the reporting level of details being only a summary and details concerning only errors and warnings (as presented above) is enough from the business perspective.
In such a case we can close (archive ;) ) this PR for eventual future use, when eg. detailed change event log envisioned above by @pablotto would start to be required.

Ok sounds good. We can keep the PR until we are sure we have a concrete business use case for the feature rather than adding complexity to the library 😉

Concerning the error / warning callbacks - it feels like the #107 would be welcome to have it done.
Also would be even more cool when the callback Exception (currently Throwable) would become some specified type

Unfortunately, the Throwable exception passed by the callback currently cannot be a more specific type since this is what the SphereClient from the commercetools-jvm-sdk throws so it won't be safe to have a lower bounded class type than Throwable.

having some update/create action context related attribute and a structured/parseable (JSON?) message.

That definitely aligns with our line of thought (and what is stated in #107): getting more context about the error in the update request (source resource draft, target resource and update actions) OR error in the create request (source resource draft). However, creating your own structured/parseable (JSON?) is something you can do within the body of the callback given the context 😉 but it should be something this library should do for you.

(especially that the exception parameter of the errorCallback appears to be optional).

That is true. In some cases we thought it's too much to throw an exception. But I think this can be definitely changed/improved to be more consistent and to always throw an exception regardless the reasons. (I added it to the issue #107.)

Could you please also put some light on warnings? What are example situations when warnings are raised?

warningCallbacks are more meant to be triggered in events in which the sync process (building actions and making a request) for syncing a resource (e.g. product) can continue even though this event has occurred. This is opposite than errorCallback which when triggered:

  • does not continue syncing the resource.
  • increments the failed statistics.

This should definitely be clearly defined and documented. (I added it to the issue #107.)

@valdemon
Copy link

@valdemon valdemon commented Nov 29, 2018 •

@heshamMassoud @jarzynp @MelNiermann Looks like even from the API perspective it's NOT possible to get the detailed information what's the exception particular cause as exactly same amount of information comes in API response (I've checked @jarzynp example with the API Playground).

That said whatever we would do here in this library we can't get more details until some error reporting improvement would take place on the API implementation side.

In current API state of the art, taking the @jarzynp example, the exception message details have no strict reference to particular payload attribute, which causes the exception:
eg: actions -> name: Missing required value points to the 1-st action in the actions array being a part of the request body (figured out by observation ;) ):

{
  "version" : 1,
  "actions" : [ {
    "action" : "changeName"
  }, {
    "action" : "removeAttributeDefinition",
    "name" : "attr_name_2"
  }, {
  ...
}

For having a strict references in the error message (or error attributes), it'd be enough to use JSONPath or JSON Pointer strings instead, eg: $.actions[0] -> name: Missing required value. or even better - enhance the structure of the SphereError class:

{
    "code" : "InvalidJsonInput",
    "message" : "Request body does not contain valid JSON.",
    "detailedErrorMessage" : "name: Missing required value",
    "path": "$.actions[0]"
  }

Having that and the request body, which is accessible from the ErrorResponseException what we receive in the callback, we would be able to construct a reliable report.
Without such a level of details looking for the actual exception reason can be time consuming for report stakeholders especially in larger UpdateActions set, not mentioning that we can't translate it into eg. JSON Patch syntax mentioned by @pablotto.

Maybe one of our first iteration outcome could be the request for this enhancement to the API maintainers? What d'you think?

@butenkor
Copy link
Member

@butenkor butenkor commented Dec 6, 2018

Also would be even more cool when the callback Exception (currently Throwable) would become some specified type

I am not sure if it makes sense for the sync to unwrap an original error (which has been produced by SDK itself) as the caller of sync might get only stripped version of the error. Currently one can decide individually how to handle it. Additionally anytime SDK would introduce new API error, sync would have to be able to map it, which would not be possible without quick fix release. Currently we have to throw Throwable as SDK itself might do it too.

For validation errors produced by the sync itself (like warning callbacks) one could consider dedicated exception types.

it would be good to have context (failing UpdateAction maybe?)

Exceptions from CTP SDK contain all the context like request/response, headers, body (where failed actions are defined). With #107 resolved one would have even more context in place.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
6 participants
You can’t perform that action at this time.