This repository has been archived by the owner on Apr 20, 2022. It is now read-only.
forked from couchbaselabs/php-ext-couchbase
-
Notifications
You must be signed in to change notification settings - Fork 32
/
views.c
425 lines (349 loc) · 11.1 KB
/
views.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
/*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright 2012 Couchbase, Inc. |
+----------------------------------------------------------------------+
| Licensed under the Apache License, Version 2.0 (the "License"); |
| you may not use this file except in compliance with the License. |
| You may obtain a copy of the License at |
| http://www.apache.org/licenses/LICENSE-2.0 |
| Unless required by applicable law or agreed to in writing, software |
| distributed under the License is distributed on an "AS IS" BASIS, |
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or |
| implied. See the License for the specific language governing |
| permissions and limitations under the License. |
+----------------------------------------------------------------------+
*/
#include "internal.h"
#include "views.h"
/* append a string literal to a smart_str */
#define APPEND_URI_s(u, s) \
smart_str_appendl(u, s, sizeof(s)-1)
typedef struct _php_couchbase_htinfo {
int htstatus;
size_t ndata;
char data[1];
} php_couchbase_htinfo;
static void php_couchbase_complete_callback(lcb_http_request_t request,
lcb_t instance,
const void *cookie,
lcb_error_t error,
const lcb_http_resp_t *resp)
{
php_couchbase_ctx *ctx = (php_couchbase_ctx *)cookie;
php_couchbase_htinfo *hti;
pcbc_stop_loop(ctx->res);
if (resp->version != 0) {
ctx->extended_value = NULL;
ctx->res->rc = LCB_ERROR;
return;
}
/* We have one extra byte in 'data' */
hti = emalloc(sizeof(*hti) + resp->v.v0.nbytes);
hti->ndata = resp->v.v0.nbytes;
if (hti->ndata) {
memcpy(hti->data, resp->v.v0.bytes, hti->ndata);
}
hti->data[hti->ndata] = '\0';
ctx->res->rc = error;
ctx->extended_value = hti;
hti->htstatus = resp->v.v0.status;
}
static int append_view_option(php_couchbase_res *res,
smart_str *uri,
const char *vopt, int nvopt, zval *input TSRMLS_DC)
{
view_param *curvp = NULL;
pcbc_sso_buf sso = { 0 };
int status;
char *error;
if (res->viewopts_passthrough == 0) {
curvp = pcbc_find_view_param(vopt, nvopt);
if (!curvp) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"Unrecognized view option '%*s'", nvopt, vopt);
return -1;
}
status = curvp->handler(curvp, input, &sso, &error TSRMLS_CC);
if (status == -1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"Problem with value for parameter '%*s': %s",
nvopt, vopt, error);
return -1;
}
} else {
pcbc_vopt_generic_param_handler(NULL,
input, &sso, &error TSRMLS_CC);
}
/**
* Otherwise, we have a string we can append..
*/
smart_str_appendl(uri, vopt, nvopt);
smart_str_appendc(uri, '=');
smart_str_appendl(uri, sso.str, sso.len);
smart_str_appendc(uri, '&');
pcbc_sso_buf_cleanup(&sso);
return 0;
}
/* }}} */
static void extract_view_options(php_couchbase_res *couchbase_res,
zval *options, char **payload,
smart_str *uri TSRMLS_DC)
{
smart_str_appendc(uri, '?');
for (zend_hash_internal_pointer_reset(Z_ARRVAL_P(options));
zend_hash_has_more_elements(Z_ARRVAL_P(options)) == SUCCESS;
zend_hash_move_forward(Z_ARRVAL_P(options))) {
char *key;
uint klen;
ulong idx;
int type;
zval **ppzval;
type = zend_hash_get_current_key_ex(Z_ARRVAL_P(options),
&key, &klen, &idx, 0, NULL);
if (type != HASH_KEY_IS_STRING || klen == 0) {
php_error_docref(NULL TSRMLS_CC, E_ERROR,
"Got non- (or empty) string value "
"for view parameters (%d)",
type);
continue;
}
if (zend_hash_get_current_data(Z_ARRVAL_P(options), (void **)&ppzval) == FAILURE) {
php_error_docref(NULL TSRMLS_CC, E_ERROR,
"Couldn't get value for %*s", klen, key);
continue;
}
if (strcasecmp("keys", key) == 0) {
smart_str buf = {0};
char *body;
lcb_size_t nbody;
pcbc_json_encode(&buf, *ppzval TSRMLS_CC);
if (buf.len == 0) {
php_error_docref(NULL TSRMLS_CC, E_ERROR,
"Failed to encode key array");
return;
}
nbody = buf.len + 15;
body = calloc(nbody, 1);
if (body == NULL) {
php_error_docref(NULL TSRMLS_CC, E_ERROR,
"Failed to allocate memory");
smart_str_free(&buf);
return;
}
sprintf(body, "{ \"keys\" : ");
strncat(body, buf.c, buf.len);
strcat(body, " }");
*payload = body;
smart_str_free(&buf);
} else {
/* Yes! The length *includes* the NUL byte */
append_view_option(couchbase_res, uri, key, klen - 1, *ppzval TSRMLS_CC);
}
}
/* trim the last '&' from the uri */
if (uri->c[uri->len - 1] == '&') {
uri->len--;
}
}
static void php_couchbase_sanitize_path(smart_str *uri,
char *doc_name, long doc_name_len,
char *view_name, long view_name_len)
{
if (strcmp(doc_name, "_all_docs") == 0) {
/* special case of _all_docs, which does not have its own design doc */
APPEND_URI_s(uri, "_all_docs");
} else if (view_name_len == 0) {
/* i.e. we only have a single argument */
smart_str_appendl(uri, doc_name, doc_name_len);
} else {
/* both design and doc. this is 'proper' usage */
APPEND_URI_s(uri, "_design/");
smart_str_appendl(uri, doc_name, doc_name_len);
APPEND_URI_s(uri, "/_view/");
smart_str_appendl(uri, view_name, view_name_len);
}
}
/**
* Extract errors from the view response and make it into a nice message.
* If we have an error and reason field, return those. Otherwise return the
* HTTP content string
*/
static char *php_couchbase_view_convert_to_error(zval *decoded,
php_couchbase_htinfo *hti)
{
char *err = NULL, *reason = NULL;
char *ret = NULL;
zval **zverr = NULL, **zvreason = NULL;
int nerr = 0, nreason = 0;
if (IS_ARRAY == Z_TYPE_P(decoded)) {
zend_hash_find(Z_ARRVAL_P(decoded),
"error", sizeof("error"),
(void **)&zverr);
zend_hash_find(Z_ARRVAL_P(decoded),
"reason", sizeof("reason"),
(void **)&zvreason);
}
if (zverr == NULL && zvreason == NULL) {
spprintf(&ret, 2048, "[%d, %*s]",
hti->htstatus, (int)hti->ndata, hti->data);
return ret;
}
if (!zverr) {
err = "Unknown Error";
nerr = strlen(err);
} else {
err = Z_STRVAL_PP(zverr);
nerr = Z_STRLEN_PP(zverr);
}
if (!zvreason) {
reason = "Unknown reason";
nreason = strlen(reason);
} else {
reason = Z_STRVAL_PP(zvreason);
nreason = Z_STRLEN_PP(zvreason);
}
spprintf(&ret, 2048, "[%d, %*s, %*s]",
hti->htstatus,
(int)nerr, err, (int)nreason, reason);
return ret;
}
struct tc_cookie {
lcb_t instance;
lcb_http_request_t request;
};
void timer_callback(lcb_timer_t timer, lcb_t instance, const void *cookie)
{
struct tc_cookie *tc = (struct tc_cookie *)cookie;
lcb_cancel_http_request(tc->instance, tc->request);
}
PHP_COUCHBASE_LOCAL
void php_couchbase_view_impl(INTERNAL_FUNCTION_PARAMETERS, int oo, int uri_only)
{
zval *options = NULL;
char *doc_name = NULL, *view_name = NULL;
long doc_name_len = 0, view_name_len = 0;
zend_bool return_errors = 0;
lcb_error_t retval;
smart_str uri = {0};
php_couchbase_res *couchbase_res;
php_couchbase_ctx ctx = {0};
lcb_http_cmd_t cmd = {0};
lcb_timer_t timer;
struct tc_cookie tcc;
char *body = NULL;
long view_timeout = INI_INT(PCBC_INIENT_VIEW_TIMEOUT);
int argflags = oo ? PHP_COUCHBASE_ARG_F_OO : PHP_COUCHBASE_ARG_F_FUNCTIONAL;
PHP_COUCHBASE_GET_PARAMS(couchbase_res, argflags, "s|sab",
&doc_name, &doc_name_len,
&view_name, &view_name_len,
&options, &return_errors);
APPEND_URI_s(&uri, "/");
php_couchbase_sanitize_path(&uri, doc_name, doc_name_len,
view_name, view_name_len);
if (options && memchr(uri.c, '?', uri.len) == NULL) {
extract_view_options(couchbase_res, options, &body, &uri TSRMLS_CC);
}
/* Strip off the '?' if it is at the end */
if (uri.len > 0 && uri.c[uri.len] == '\0' && uri.c[uri.len - 1] == '?') {
--uri.len;
}
if (uri_only) {
/**
* Because PHP apparently has multiple personality disorder
* when it comes to the memory allocators it uses, we'll need
* to copy and free the buf
*/
ZVAL_STRINGL(return_value, uri.c, uri.len, 1);
smart_str_free(&uri);
return;
}
ctx.res = couchbase_res;
memset(&cmd, 0, sizeof(cmd));
cmd.v.v0.path = uri.c;
cmd.v.v0.npath = uri.len;
cmd.v.v0.body = body;
if (body) {
cmd.v.v0.nbody = strlen(body);
cmd.v.v0.method = LCB_HTTP_METHOD_POST;
} else {
cmd.v.v0.method = LCB_HTTP_METHOD_GET;
}
cmd.v.v0.content_type = "application/json";
retval = lcb_make_http_request(couchbase_res->handle,
(const void *)&ctx,
LCB_HTTP_TYPE_VIEW,
&cmd, &tcc.request);
smart_str_free(&uri);
free(body);
if (retval != LCB_SUCCESS) {
couchbase_res->rc = retval;
couchbase_report_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo,
cb_lcb_exception,
"Failed to schedule couch request: %s",
lcb_strerror(couchbase_res->handle, retval));
return ;
}
/* Setup a timer to monitor the progress of the view request */
tcc.instance = couchbase_res->handle;
/* @todo: When we allow the user to specify connection_timeout
* as a parameter, we should ensure that the timer
* is set higher than that.
*/
/*
* The view timeout is specified in secs, libcouchbase timers
* operate in the usec range
*/
view_timeout *= 1000000;
timer = lcb_timer_create(couchbase_res->handle, &tcc,
view_timeout, 0, timer_callback,
&retval);
if (retval != LCB_SUCCESS) {
couchbase_res->rc = retval;
lcb_cancel_http_request(tcc.instance, tcc.request);
couchbase_report_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo,
cb_lcb_exception,
"Failed to setup timer to monitor view request: %s",
lcb_strerror(couchbase_res->handle, retval));
return;
}
/* Run the view */
pcbc_start_loop(couchbase_res);
lcb_timer_destroy(couchbase_res->handle, timer);
if (ctx.extended_value) {
php_couchbase_htinfo *hti = ctx.extended_value;
pcbc_json_decode(return_value, hti->data, hti->ndata, 1 TSRMLS_CC);
if ((ctx.res->rc != LCB_SUCCESS || (hti->htstatus) / 100 != 2) && return_errors == 0) {
char *errstr = php_couchbase_view_convert_to_error(return_value,
hti);
zval_dtor(return_value);
ZVAL_FALSE(return_value);
couchbase_report_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo,
cb_server_exception, "%s", errstr);
efree(errstr);
}
efree(hti);
return;
} else {
ZVAL_FALSE(return_value);
couchbase_report_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo,
cb_lcb_exception, "Failed to execute view: %s",
lcb_strerror(couchbase_res->handle,
ctx.res->rc));
}
}
#undef APPEND_URI_s
PHP_COUCHBASE_LOCAL
void php_couchbase_callbacks_view_init(lcb_t handle)
{
lcb_set_http_complete_callback(handle, php_couchbase_complete_callback);
}
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet expandtab sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/