Module: Agoo::Server

Defined in:
ext/agoo/rserver.c

Class Method Summary collapse

Class Method Details

.add_mime(suffix, type) ⇒ Object

call-seq: add_mime(suffix, type)

Adds a mime type by associating a type string with a suffix. This is used for static files.



1001
1002
1003
1004
1005
1006
1007
1008
1009
# File 'ext/agoo/rserver.c', line 1001

static VALUE
add_mime(VALUE self, VALUE suffix, VALUE type) {
    struct _agooErr	err = AGOO_ERR_INIT;

    if (AGOO_ERR_OK != mime_set(&err, StringValuePtr(suffix), StringValuePtr(type))) {
	rb_raise(rb_eArgError, "%s", err.msg);
    }
    return Qnil;
}

.domain(host, path) ⇒ Object

call-seq: domain(host, path)

Sets up a sub-domain. The first argument, host should be either a String or a Regexp that includes variable replacement elements. The path argument should also be a string. If the host argument is a Regex then the $(n) sequence will be replaced by the matching variable in the Regex result. The path is the root of the sub-domain.



1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
# File 'ext/agoo/rserver.c', line 1086

static VALUE
domain(VALUE self, VALUE host, VALUE path) {
    struct _agooErr	err = AGOO_ERR_INIT;

    switch(rb_type(host)) {
    case RUBY_T_STRING:
	rb_check_type(path, T_STRING);
	if (AGOO_ERR_OK != agoo_domain_add(&err, rb_string_value_ptr((VALUE*)&host), rb_string_value_ptr((VALUE*)&path))) {
	    rb_raise(rb_eArgError, "%s", err.msg);
	}
	break;
    case RUBY_T_REGEXP: {
	volatile VALUE	v = rb_funcall(host, rb_intern("inspect"), 0);
	char		rx[1024];

	if (sizeof(rx) <= RSTRING_LEN(v)) {
	    rb_raise(rb_eArgError, "host Regex limited to %ld characters", sizeof(rx));
	}
	strcpy(rx, rb_string_value_ptr((VALUE*)&v) + 1);
	rx[RSTRING_LEN(v) - 2] = '\0';
	if (AGOO_ERR_OK != agoo_domain_add_regex(&err, rx, rb_string_value_ptr((VALUE*)&path))) {
	    rb_raise(rb_eArgError, "%s", err.msg);
	}
	break;
    }
    default:
	rb_raise(rb_eArgError, "host must be a String or Regex");
	break;
    }
    return Qnil;
}

.handle(method, pattern, handler) ⇒ Object

call-seq: handle(method, pattern, handler)

Registers a handler for the HTTP method and path pattern specified. The path pattern follows glob like rules in that a single * matches a single token bounded by the ‘/` character and a double ** matches all remaining.



890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
# File 'ext/agoo/rserver.c', line 890

static VALUE
handle(VALUE self, VALUE method, VALUE pattern, VALUE handler) {
    agooHook	hook;
    agooMethod	meth = AGOO_ALL;
    const char	*pat;
    ID		static_id = rb_intern("static?");

    rb_check_type(pattern, T_STRING);
    pat = StringValuePtr(pattern);

    if (connect_sym == method) {
	meth = AGOO_CONNECT;
    } else if (delete_sym == method) {
	meth = AGOO_DELETE;
    } else if (get_sym == method) {
	meth = AGOO_GET;
    } else if (head_sym == method) {
	meth = AGOO_HEAD;
    } else if (options_sym == method) {
	meth = AGOO_OPTIONS;
    } else if (post_sym == method) {
	meth = AGOO_POST;
    } else if (put_sym == method) {
	meth = AGOO_PUT;
    } else if (Qnil == method) {
	meth = AGOO_ALL;
    } else {
	rb_raise(rb_eArgError, "invalid method");
    }
    if (T_STRING == rb_type(handler)) {
	handler = resolve_classpath(StringValuePtr(handler), RSTRING_LEN(handler));
    }
    if (rb_respond_to(handler, static_id)) {
	if (Qtrue == rb_funcall(handler, static_id, 0)) {
	    VALUE	res = rb_funcall(handler, call_id, 1, Qnil);
	    VALUE	bv;

	    rb_check_type(res, T_ARRAY);
	    if (3 != RARRAY_LEN(res)) {
		rb_raise(rb_eArgError, "a rack call() response must be an array of 3 members.");
	    }
	    bv = rb_ary_entry(res, 2);
	    if (T_ARRAY == rb_type(bv)) {
		int		i;
		int		bcnt = (int)RARRAY_LEN(bv);
		agooText	t = agoo_text_allocate(1024);
		struct _agooErr	err = AGOO_ERR_INIT;
		VALUE		v;

		if (NULL == t) {
		    rb_raise(rb_eArgError, "failed to allocate response.");
		}
		for (i = 0; i < bcnt; i++) {
		    v = rb_ary_entry(bv, i);
		    t = agoo_text_append(t, StringValuePtr(v), (int)RSTRING_LEN(v));
		}
		if (NULL == t) {
		    rb_raise(rb_eNoMemError, "Failed to allocate memory for a response.");
		}
		if (NULL == agoo_page_immutable(&err, pat, t->text, t->len)) {
		    rb_raise(rb_eArgError, "%s", err.msg);
		}
		agoo_text_release(t);

		return Qnil;
	    }
	}
    }
    if (NULL == (hook = rhook_create(meth, pat, handler, &agoo_server.eval_queue))) {
	rb_raise(rb_eStandardError, "out of memory.");
    } else {
	agooHook	h;
	agooHook	prev = NULL;

	for (h = agoo_server.hooks; NULL != h; h = h->next) {
	    prev = h;
	}
	if (NULL != prev) {
	    prev->next = hook;
	} else {
	    agoo_server.hooks = hook;
	}
	rb_gc_register_address((VALUE*)&hook->handler);
    }
    return Qnil;
}

.handle_not_found(handler) ⇒ Object

call-seq: not_found_handle(handler)

Registers a handler to be called when no other hook is found and no static file is found.



984
985
986
987
988
989
990
991
992
# File 'ext/agoo/rserver.c', line 984

static VALUE
handle_not_found(VALUE self, VALUE handler) {
    if (NULL == (agoo_server.hook404 = rhook_create(AGOO_GET, "/", handler, &agoo_server.eval_queue))) {
	rb_raise(rb_eStandardError, "out of memory.");
    }
    rb_gc_register_address((VALUE*)&agoo_server.hook404->handler);

    return Qnil;
}

.header_rule(path, mime, key, value) ⇒ Object

call-seq: header_rule(path, mime, key, value)

Add a header rule. A header rule will add the key and value to the headers of any static asset that matches the path and mime type specified. The path pattern follows glob like rules in that a single * matches a single token bounded by the ‘/` character and a double ** matches all remaining. The mime can also be a * which matches all types. The mime argument will be compared to the mine type as well as the file extension so ’applicaiton/json’, a mime type can be used as can ‘json’ as a file extension. All rules that match add the header key and value to the header of a static asset.

Note that the server must be initialized before calling this method.



1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
# File 'ext/agoo/rserver.c', line 1061

static VALUE
header_rule(VALUE self, VALUE path, VALUE mime, VALUE key, VALUE value) {
    struct _agooErr	err = AGOO_ERR_INIT;

    rb_check_type(path, T_STRING);
    rb_check_type(mime, T_STRING);
    rb_check_type(key, T_STRING);
    rb_check_type(value, T_STRING);

    if (AGOO_ERR_OK != agoo_header_rule(&err, StringValuePtr(path), StringValuePtr(mime), StringValuePtr(key), StringValuePtr(value))) {
	rb_raise(rb_eArgError, "%s", err.msg);
    }
    return Qnil;
}

.init(*args) ⇒ Object

call-seq: init(port, root, options)

Configures the server that will listen on the designated port and using the root as the root of the static resources. This must be called before using other server methods. Logging is feature based and not level based and the options reflect that approach. If bind option is to be used instead of the port then set the port to zero.

  • options [Hash] server options

    • :pedantic [true|false] if true response header and status codes are checked and an exception raised if they violate the rack spec at github.com/rack/rack/blob/master/SPEC, tools.ietf.org/html/rfc3875#section-4.1.18, or tools.ietf.org/html/rfc7230.

    • :thread_count [Integer] number of ruby worker threads. Defaults to one. If zero then the start function will not return but instead will proess using the thread that called start. Usually the default is best unless the workers are making IO calls.

    • :worker_count [Integer] number of workers to fork. Defaults to one which is not to fork.

    • :bind [String|Array] a binding or array of binds. Examples are: “http ://127.0.0.1:6464”, “unix:///tmp/agoo.socket”, “http ://[::1]:6464, or to not restrict the address ”http ://:6464“.

    • :graphql [String] path to GraphQL endpoint if support for GraphQL is desired.



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
# File 'ext/agoo/rserver.c', line 262

static VALUE
rserver_init(int argc, VALUE *argv, VALUE self) {
    struct _agooErr	err = AGOO_ERR_INIT;
    int			port;
    const char		*root;
    VALUE		options = Qnil;

    if (argc < 2 || 3 < argc) {
	rb_raise(rb_eArgError, "Wrong number of arguments to Agoo::Server.configure.");
    }
    port = FIX2INT(argv[0]);
    rb_check_type(argv[1], T_STRING);
    root = StringValuePtr(argv[1]);
    if (3 <= argc) {
	options = argv[2];
    }
    if (AGOO_ERR_OK != agoo_server_setup(&err)) {
	rb_raise(rb_eStandardError, "%s", err.msg);
    }
    agoo_server.ctx_nil_value = (void*)Qnil;
    agoo_server.env_nil_value = (void*)Qnil;

    if (AGOO_ERR_OK != configure(&err, port, root, options)) {
	rb_raise(rb_eArgError, "%s", err.msg);
    }
    agoo_server.inited = true;

    return Qnil;
}

.path_group(path, dirs) ⇒ Object

call-seq: path_group(path, dirs)

Sets up a path group where the path defines a group of directories to search for a file. For example a path of ‘/assets’ could be mapped to a set of [ ‘home/user/images’, ‘/home/user/app/assets/images’ ].



1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
# File 'ext/agoo/rserver.c', line 1019

static VALUE
path_group(VALUE self, VALUE path, VALUE dirs) {
    struct _agooErr	err = AGOO_ERR_INIT;
    agooGroup		g;

    rb_check_type(path, T_STRING);
    rb_check_type(dirs, T_ARRAY);

    if (NULL != (g = agoo_group_create(StringValuePtr(path)))) {
	int	i;
	int	dcnt = (int)RARRAY_LEN(dirs);
	VALUE	entry;

	for (i = dcnt - 1; 0 <= i; i--) {
	    entry = rb_ary_entry(dirs, i);
	    if (T_STRING != rb_type(entry)) {
		entry = rb_funcall(entry, rb_intern("to_s"), 0);
	    }
	    if (NULL == agoo_group_add(&err, g, StringValuePtr(entry))) {
		rb_raise(rb_eStandardError, "%s", err.msg);
	    }
	}
    }
    return Qnil;
}

.rack_early_hints(on) ⇒ Object

call-seq: rack_early_hints(on)

Turns on or off the inclusion of a early_hints object in the rack call env Hash. If the argument is nil then the current value is returned.



1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
# File 'ext/agoo/rserver.c', line 1125

static VALUE
rack_early_hints(VALUE self, VALUE on) {
    if (Qtrue == on) {
	agoo_server.rack_early_hints = true;
    } else if (Qfalse == on) {
	agoo_server.rack_early_hints = false;
    } else if (Qnil == on) {
	on = agoo_server.rack_early_hints ? Qtrue : Qfalse;
    } else {
	rb_raise(rb_eArgError, "rack_early_hints can only be set to true or false");
    }
    return on;
}

.shutdownObject

call-seq: shutdown()

Shutdown the server. Logs and queues are flushed before shutting down.



838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
# File 'ext/agoo/rserver.c', line 838

VALUE
rserver_shutdown(VALUE self) {
    if (agoo_server.inited) {
	agoo_server_shutdown("Agoo", stop_runners);

	if (1 < the_rserver.worker_cnt && getpid() == *the_rserver.worker_pids) {
	    int	i;
	    int	status;
	    int	exit_cnt = 1;
	    int	j;

	    for (i = 1; i < the_rserver.worker_cnt; i++) {
		kill(the_rserver.worker_pids[i], SIGKILL);
	    }
	    for (j = 0; j < 20; j++) {
		for (i = 1; i < the_rserver.worker_cnt; i++) {
		    if (0 == the_rserver.worker_pids[i]) {
			continue;
		    }
		    if (0 < waitpid(the_rserver.worker_pids[i], &status, WNOHANG)) {
			if (WIFEXITED(status)) {
			    //printf("exited, status=%d for %d\n", agoo_server.worker_pids[i], WEXITSTATUS(status));
			    the_rserver.worker_pids[i] = 0;
			    exit_cnt++;
			} else if (WIFSIGNALED(status)) {
			    //printf("*** killed by signal %d for %d\n", agoo_server.worker_pids[i], WTERMSIG(status));
			    the_rserver.worker_pids[i] = 0;
			    exit_cnt++;
			}
		    }
		}
		if (the_rserver.worker_cnt <= exit_cnt) {
		    break;
		}
		dsleep(0.2);
	    }
	    if (exit_cnt < the_rserver.worker_cnt) {
		printf("*-*-* Some workers did not exit.\n");
	    }
	}
    }
    return Qnil;
}

.startObject

call-seq: start()

Start the server.



728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
# File 'ext/agoo/rserver.c', line 728

static VALUE
rserver_start(VALUE self) {
    VALUE		*vp;
    int			i;
    int			pid;
    double		giveup;
    struct _agooErr	err = AGOO_ERR_INIT;
    VALUE		agoo = rb_const_get_at(rb_cObject, rb_intern("Agoo"));
    VALUE		v = rb_const_get_at(agoo, rb_intern("VERSION"));

    *the_rserver.worker_pids = getpid();

    // If workers then set the loop_max based on the expected number of
    // threads per worker.
    if (1 < the_rserver.worker_cnt) {
	agoo_server.loop_max /= the_rserver.worker_cnt;
	if (agoo_server.loop_max < 1) {
	    agoo_server.loop_max = 1;
	}
    }
    if (AGOO_ERR_OK != setup_listen(&err)) {
	rb_raise(rb_eIOError, "%s", err.msg);
    }
    for (i = 1; i < the_rserver.worker_cnt; i++) {
	VALUE	rpid = rb_funcall(rb_cObject, rb_intern("fork"), 0);

	if (Qnil == rpid) {
	    pid = 0;
	} else {
	    pid = NUM2INT(rpid);
	}
	if (0 > pid) { // error, use single process
	    agoo_log_cat(&agoo_error_cat, "Failed to fork. %s.", strerror(errno));
	    break;
	} else if (0 == pid) {
	    if (AGOO_ERR_OK != agoo_log_start(&err, true)) {
		rb_raise(rb_eStandardError, "%s", err.msg);
	    }
	    break;
	} else {
	    the_rserver.worker_pids[i] = pid;
	}
    }
    if (AGOO_ERR_OK != agoo_server_start(&err, "Agoo", StringValuePtr(v))) {
	rb_raise(rb_eStandardError, "%s", err.msg);
    }
    if (0 >= agoo_server.thread_cnt) {
	agooReq	req;

	while (agoo_server.active) {
	    if (NULL != (req = (agooReq)agoo_queue_pop(&agoo_server.eval_queue, 0.1))) {
		handle_protected(req, false);
		agoo_req_destroy(req);
	    } else {
		rb_thread_schedule();
	    }
	    if (agoo_stop) {
		agoo_shutdown();
		break;
	    }
	}
    } else {
	if (NULL == (the_rserver.eval_threads = (VALUE*)AGOO_MALLOC(sizeof(VALUE) * (agoo_server.thread_cnt + 1)))) {
	    rb_raise(rb_eNoMemError, "Failed to allocate memory for the thread pool.");
	}
	for (i = agoo_server.thread_cnt, vp = the_rserver.eval_threads; 0 < i; i--, vp++) {
	    *vp = rb_thread_create(wrap_process_loop, NULL);
	}
	*vp = Qnil;

	giveup = dtime() + 1.0;
	while (dtime() < giveup) {
	    // The processing threads will not start until this thread
	    // releases ownership so do that and then see if the threads has
	    // been started yet.
	    rb_thread_schedule();
	    if (2 + agoo_server.thread_cnt <= (long)atomic_load(&agoo_server.running)) {
		break;
	    }
	}
    }
    return Qnil;
}