Problem
Much like the problem outlined in #2608610: Add support for list/item pattern, we have a need to import a bunch of items where the full list of those items (with minimal metadata like id) is defined in an endpoint like:
And each item can be retrieved in full as a single JSON object via:
I have looked into the solution on that issue, and it looks promising, however - the latest patches don't apply. And I feel like the idea of defining uri templates and child item selectors is adding complexity without addressing all use cases where we want to dynamically generate the source URLs.
Also - the item endpoint I am using provides just a single JSON object, not an array as the Json data parser assumes.
Proposed solution
Lets just allow the Url processor to take a callback which can do the work of generating the URLs in advance.
This would have other benefits (in addition to providing a way for you to implentment the ItemList Item pattern), for example, if you wish your list of source URLs to be paginated from a source, for example you are importing a catalog of 10,000 products and you want to do in batches of 200 (to balance memory limitations with the economy of making fewer HTTP requests) your callback could handle generating the urls. Each URL might looks like:
- https://source.data.com/api/items?start=1&end=200
- https://source.data.com/api/items?start=201&end=400
- ...
The other part of the solution would require a way to configure the migration so that it knows a source URL might contain a single object. We could explicitly set item_selector to FALSE to indicate this.
To get this working the source configuration would be something like:
source:
plugin: url
data_fetcher_plugin: http
data_parser_plugin: json
urls:
callback: my_module_migrate_urls
item_selector: false
skip_count: true
Note: skip_count: true is important if you have a large number of URLs, otherwise things like drush migrate-status will iterate through all requested URLs to get a total count.
The current migration is passed to the callback, this will allow some other tweaking, like ensuring only URLs we intend to import in the current migration are imported, like so:
use Drupal\migrate\Plugin\MigrationInterface
use Drupal\migrate\Plugin\MigrateIdMapInterface
function my_module_migrate_urls(MigrationInterface $migration) {
$ids = my_module_get_all_ids();
$urls = [];
// Lets exclude URLs for items already marked as imported.
$id_map = $migration->getIdMap();
$imported_ids = $id_map->getDatabase()->select($id_map->mapTableName(), 'm')
->fields('m', ['sourceid1'])
->condition('source_row_status', MigrateIdMapInterface::STATUS_IMPORTED)
->execute()
->fetchCol();
$ids = array_diff($ids, $imported_ids);
foreach ($ids as $id) {
$urls[] = "https://example.com/jsonapi/node/article/{$id}";
}
return $urls;
}
Issue fork migrate_plus-3040427
Show commands
Start within a Git clone of the project using the version control instructions.
Or, if you do not have SSH keys set up on git.drupalcode.org:
Comments
Comment #2
daniel.rolls@flightcentre.com.au commentedI have attached a patch which will allow this pattern you as detailed:
The function my_module_migrate_urls should return an array of source URLs.
When using this pattern I would suggest using the config:
This will prevent all the source URLs being requested during a:
Comment #3
daniel.rolls@flightcentre.com.au commentedComment #4
sphism commentedThat's a pretty elegant solution to both the list/item pattern and the pagination issue, I like it
Comment #5
heddnSo, I like the idea. But it needs some help with the documentation (doxygen examples?) and some tests.
Comment #6
daniel.rolls@flightcentre.com.au commentedComment #7
daniel.rolls@flightcentre.com.au commentedHey I have added some documentation to the URL class (following examples in SourcePluginBase)
Have also updated to:
Comment #8
daniel.rolls@flightcentre.com.au commentedPatching against 8.x-5.x.
(patch is the same as 8.x-4.x)
Comment #9
daniel.rolls@flightcentre.com.au commentedComment #10
daniel.rolls@flightcentre.com.au commentedHad some incorrect test method descriptions in that pull request. Updating to correct (with backport to 8.4)
Comment #11
daniel.rolls@flightcentre.com.au commentedComment #12
heddnNice API addition. Some minor feedback. Also there are php code standard violations. See https://www.drupal.org/files/issues/2019-09-02/migrate_plus-8.x-5.x-sour...
This seems dense at the end. What about, "callback that returns a list of urls?
Let's move this text below the code examples. That's how I normally see this done in drupal's doxygen.
I don't think need to explain the concept of a PHP callback.
This isn't needed. We're not dealing with a drupal to drupal upgrade and that is the only thing that requires this. At the very least, it should be discussed in another issue.
If it is set, but not callable, we should throw an InvalidPluginException..
And we should allow a list of callbacks that we can iterator over. Then use call_user_func or call_user_func_array as appropriate.
Let's add explicit test coverage for class based callbacks and methods.
Why is this added? It seems like a strange addition.
This seems like a strange addition here.
Let's use a data provider here instead of private arrays.
https://phpunit.readthedocs.io/en/8.3/writing-tests-for-phpunit.html#dat...
Comment #13
agentrickardI'm testing this, and hope to do the refactor in #12, and I've also run into an issue that perhaps someone can explain:
* I have a list of URLs to iterate over. That works fine.
* 1000 of these URLs return the expected JSON object, which is a nested set of objects that need to be iterated over normally.
* N of these URLs return an exception from the _api server_ that is not in the format the migration expects.
It seems that all we do in that case is throw an exception, which halts the migration.
That's problematic when the error occurs on record 3 of 1,000. The migration never can run.
The problem here is that we don't know if the URL will return valid JSON until we run the data_fetcher on the URLs list. Passing a fake object and returning FALSE from hook_migrate_prepare_row() doesn't quite work, because Migrate still tries to save a non-existent sourceID to the mapping table.
Am I overlooking something? Is there a means at the data_fetcher or data_parser level to tell Migrate to skip a well-formed but unexpected JSON object?
Comment #14
heddnRe #13: does #3092369: Add continue-on-failure option help at all?
Comment #15
agentrickardIt doesn't seem to. Though I had to backport that patch to Drush 8 due to dependency chains.
Drush 8 patch uploaded to other issue.
Comment #16
hudriThis idea is plain genius. This will not only fit for paged sources, this fits also solutions where the source requires a dynamic date parameter, e.g. urls like
/json/data?last_changed=timestampor/json/events/?from=date1&to=date2I've already three homegrown data fetcher plugins extented from http that replace tokens inside the URL. All of them can be replaced with this patch.Comment #17
agentrickardHere's a reroll of the patch from #10, with some comments regarding #12.
I disagree here. We've been using this patch for a while and there aren't any use-cases I can see where this need can't be handled by the callback itself. No need to clutter up our base code with that kind of edge case.
In this context,
$this->sourceUrlsis private, so this method is used by the test to retrieve that value. We could make$sourceUrlspublic instead.This part of the code is absolutely crucial. The issue with the JSON parser -- and perhaps others? -- is that it assumes it will receive an array of JSON objects. The use-case for this patch is that a single API call returns a single object, which the JSON data_parser will choke on, since it assumes an array.
The other option here would be some configuration indicator that a single object is expected rather than an array.
Comment #18
agentrickardLast patch is malformed.
Comment #19
agentrickardLet's try that again. Comments in #17 still stand.
Comment #20
agentrickardReroll for 8.4.x
Comment #21
agentrickardDear god I hate patch workflows. Is there a Git branch I can push to?
Comment #22
agentrickardComment #23
agentrickardComment #24
agentrickardWrong file.
Comment #25
agentrickard8.4 patch
Really, is there a Git repo I can fork?
Comment #26
agentrickardComment #27
heddnComment #28
heddnSeems like linting issues w/ last patch. Back to NW.
Comment #29
jacobbell84 commentedFixing the linting issue with patch 26.
Comment #30
jacobbell84 commentedFixing the code style warnings.
Comment #31
jacobbell84 commentedHopefully fixing last of the coding standards issues.
Comment #32
jacobbell84 commentedLast coding standards fix!
Comment #33
roam2345 commentedSeems like the --update flag is ignored with the template as provided above.
need to somehow in here ignore the array_diff if the drush --update flag is used.
Comment #34
roam2345 commentedAnother issue is that the hook my_module_migrate_urls is called on every single page load. This intern means that the function that retrieves all the my_module_get_all_ids is also fired on every page load. Logically that function is also looking up ID's of an alternate endpoint.
Not sure how best work around this.
Comment #35
hudri@lathan, the given callback function is just an example for custom logic. Just skip the
array_diffpart, if you don't need it. Migrate core'strack_changes: trueand the--updateflag work perfectly without it.Regarding #34, have you added
skip_count: true?Comment #36
roam2345 commented@hundri Yes I have that skip_count: true set.
Basically we have an external API structured like Drupals, Where by we have a list of all ID's on a URL and then a details endpoint for each Item. What we are doing with this patch is getting the list of ID's following that template code, Populating the urls under the source in config. Then it goes off and fetches each record.
This is working as laid out here. However every single bootstrap of drupal calls the callback listed in source urls config as specced. This means it's causing a cURL/guzzel request every single page load (because im fetching the list of ID's here from a URL).
Things get even worse if the API is down where by every page load now needs to wait for that request to time out.
Comment #37
roam2345 commentedRight i figured out all my issues I had custom code in our stack using the subscriber interface on onTerminate firing off the migration process. Producing the issue of calling this service on every page load. So that issue was mine (my bad).
I did however add to this patch that the __toString of the URL is validated not to be empty. Incase like us we use an endpoint to populate the URLS, and that has a connection issue or times out.
Comment #38
achapThank you for this patch. It works great however, I have one issue with it. @rollsd mentioned his data source was an object rather than an array. I don't think we can make the assumption that the parsable data is at the root of the response though. My parsable data is also an object, however it sits under another key "data" in the returned response. In that case, simply passing item_selector: FALSE does not work. I propose the addition of a new configuration key, something like item_selector_is_object, which if true will wrap the configured item_selector in an array. Obviously, we would need to ensure this still works with objects at the root of the response.
Comment #39
achapComment #40
heddnThe great gitlab migration is upon us. Please visit https://gitlab.com/drupalspoons/migrate_plus/-/issues/177 to continue the conversation. The latest patch from here has been conveniently uploaded over there to https://gitlab.com/drupalspoons/migrate_plus/-/merge_requests/3.
Comment #41
steinmb commentedReading through the Drupalspoons issue, with the state we now have on d.o. perhaps we should reopen the issue here and create MR from here? The feature req. it still useful and from what I can see, we still do not have a good alternative?
Comment #42
steinmb commentedManual reroll and minor changes just to get the ball rolling. My local tests are still running so partly untested.
Comment #43
Aaron23 commented@Steinmb Agreed. This patch needs to be updated in module. As there are scenario to keep the urls fetch from backend configuration. the custom callback will be the solution to achieve it
Comment #44
jcandan commentedAm I correct that the list of URLs created for a combination of list/item pattern and pagination would be something like this?
If the URL callback just does the job of listing all these endpoints, does anyone see a potential source data handling conflict by treating the list and item responses the same? Seems the separate solutions offered by #2608610: Add support for list/item pattern and #2640516: Support paging through multiple requests might solve for that, but I am open to getting a better grasp of this solution.
Thoughts?
Comment #45
jcandan commentedActually, come to think of it, the list/item solution I went with was a variation of the
UrlPerRowexample in Drupal Answer link from #26 of #2608610: Add support for list/item pattern.Comment #46
amaisano commentedWe wrote a similar plugin extension that provides a list of URLs back to the main source plugin. There hasn't been any conflict with # of items found vs. imported vs. any other status - it just works like normal.
We've extended the the
migrate_plug\data_parser\JSON plugin, and altered the nextSource() method to build this list.We are crawling a JSON:API in our custom plugin until we find no more "next-page" attributes in the JSON response, and then compile the full list of URLs as basically a bunch of offset page requests.
Results:
I can share the code if anyone is interested.
Comment #47
matthieuscarset commented@amaisano id very much like to read the code of this custom JSON plugin! :)
Comment #48
oivanov commented@amaisano me too! please share the code of this custom JSON plugin!
Comment #49
jcarrasco commentedI tried this patch (42, 3040427-42-migrate_plus_multiple_urls.patch) and code for function my_module_migrate_urls but I have this error:
In Url.php line 88:
The URL callback function is not callable.
What I am missing to make callback function callable?
Thanks in advance
Comment #50
amaisano commentedHere is the parser code plugin we made that handles custom/dynamic/multiple source urls:
https://www.drupal.org/project/migration_jsonapi
Comment #51
hudriWe are using patch #42 for years now very successfully with many different endpoints. Moving to reviewed & tested.
Migrate sources are so vastly different that - for me - it is much easier and faster to write a PHP callback than to find and study and update 437 different list/item source plugin modules. And very often those plugins are NOT (re-) usable because endpoint A returns an array [] on root, endpoint B returns an object {} on root, endpoint C returns an HTTP-Code 404 when the last page number was passed and endpoint D just returns an HTTP 200 with no content after the last page. PHP callbacks just work. For years. (Sorry for the rant, but the more different sources you have to migrate from, the more useful this simple patch is.)
+1 from me to include this feature into migrate_plus.
Comment #52
codechefmarcWe are also using this patch to great success. I am curious if it's possible to add an argument that can be passed to the callback as well. Our use case is that we have several migrations that all use very similar code, but have different endpoints to get different resources. So, I envision something like this:
And then in the callback function:
This may be another issue/MR, but wanted to see if anyone else had this kind of use case. At the moment, the workaround is for us to use multiple callback functions, one for each migration.
Comment #53
codechefmarcI just did a test and I can do something like this and it works - not sure how valid it is though:
Migration yml:
Callback function:
Comment #54
joachim commentedRather than load up a potentially HUGE list of URLs into the configuration, we should defer this to getSourceUrls(), and the fetchers should call that.
Also, changing configuration feels a bit ick -- it should remain what it was set to in the plugin definition rather than being spookily changed.
Comment #56
codechefmarcHi, finding out what I can do to help to move this forward - I'm planning on needing this functionality in another contrib module I'm working on. I'm not as well versed in these kinds of migrate plugins so I'm trying to follow your comment about deferring to getSourceUrls(). I see that function in there, but it's not being used anywhere. And not sure how to change the configuration piece either?
What if we made this a separate plugin that is a different name but extends the URL plugin and that way the original class isn't changed but the new one can add this functionality?
Thanks!
Comment #57
joachim commented> What if we made this a separate plugin that is a different name but extends the URL plugin and that way the original class isn't changed but the new one can add this functionality?
That's not going to work because we also need to change the DataParserPluginBase. Currently it lifts the 'urls' property directly from the Url.
We need to decouple them a little bit and have the parser plugin call a method on the URL plugin.
Comment #58
joachim commentedI've done a bit more work on this, but it turns out that adding a method to the Url source plugin class has repercussions.
We need the parser plugin to have the url source plugin object, and that means:
- DataParserPluginManager needs to implement createInstance() to receive it and pass it on to the parser plugin
- the kernel tests will all need tweaking because many of them create an instance of the parser
Would be good to get input from maintainers before I go further on this.
Comment #59
jacobbell84 commentedMaking a quick update to the existing patch to work with the new function format. While the patch was still applying before, the variable names in the getSourceData function had changed so the code wasn't actually doing anything.
Comment #60
jacobbell84 commentedComment #61
bdh676 commentedWas using patch #42 - Now fails with v6.0.7 release, migrate tools 6.1.1 release
Comment #62
bdh676 commentedComment #63
heddnwhat are the failures?
Comment #64
bdh676 commentedThe only error I am seeing in composer is this:
With the new Migrate tools update, I see the following error when trying to run cron:
Comment #65
heddnThe patch or MR probably needs a rebase then.
Comment #66
blade_ukraine commentedI've updated patch.
Comment #67
very_random_man commentedPatch in #66 doesn't apply to v6.0.5.
Comment #69
ethantRolled one for 6.0
Comment #70
heddnBut the patch needs to be rolled into an MR to ever stand a hope of getting merged. We do that so it has tests run and is reviewable. Leaving at NW for this next task.
Comment #73
rpayanmI have created a MR, please review.
Comment #74
heddnComment posted.
Comment #75
heddnComment #77
grimreaperHi,
I have rebase the MR https://git.drupalcode.org/project/migrate_plus/-/merge_requests/149 as it does not apply anymore on 6.0.11 version.